Zaratruta Zaratruta - 1 year ago 68
C Question

Function parameters without types in C programming language

Let us consider the following program:


int test(a,b,c)
return a+b+c;

int main()

I didn't know that it is possible to specify functions in C without defining the types of its parameters. This is a feature of ANSI C? Can someone explain this to me?

I thought it was not possible to do that. However, my compiler can compile this program! In which situations I can do that?

Also, The program behaviour is a little weird. When I use integer values, the function does what we expect. However, when I use float parameters, the result is very different from what I would expect.

Answer Source

If you compile this code using GCC, it will show a warnings like type of 'a' defaults to ‘int’, since C implicitly assumes type of arguments as int, when not specified.

The feature where you don't have to specify the type of an argument in a function was added in order to provide backwards compatibility with older versions of the language, the K&R version of the language. When GCC encounters an "old style" function, it conforms to the old K&R C behaviour which implies no warnings in this situation.

One possible reason why you are getting undefined results maybe because the calling code doesn't know that it needs to cast the arguments to int and hence passes float instead. Your function test then either reads registers/stack locations that floats weren't copied to or receives the bit representations of float arguments and treats them as an int. Either of these will result in incorrect values of a, b, c being received.

Note that if you explicitly specify the type of arguments like int test(int a, int b, int c), then it would type-cast the floats, and then pass them to the function, with output 5.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download