views:

93

answers:

2

Look at the following program.

int main()
{
    char a=65, ch ='c';
    printit(a,ch);
}

printit(a,ch)
{
    printf("a=%d   ch=%c",a,ch);
}

Even if the data type of the arguments is not specified in the function 'printit()', the result is shown on printf. I see correct answer when i compile it with gcc and run it.Why? Is it not necessary to specify the data type of arguments in C ? What is the default datatype of argument taken in the case shown above?

+3  A: 

The only default datatype assumed in C is int as in the code above.

Newer versions of C++ prohibit implicit data typing and newer C++ compilers refuse to compile the code above.

sharptooth
It looks like this might stop working in newer versions of C, as well. The 2005 C99+TC1+TC2 standard mentions in the forward that one of the changes from previous versions was to "Remove implicit function declaration[s]".
Nate Kohl
+1  A: 

Because you don't specify a prototype for printit(), compiler makes up implicit declaration:

int printit(int, int);

When later compiler sees the definition of printit() function without types for arguments, it uses that implicit declaration.

It is very dangerous technique - you basically prohibit type checking for this function.

qrdl
Sounds cool, but how could one prove that it works like that and arguments are not plain int? I tried to check - sizeof(a) and sizeof(ch) is 4 inside the function, so at least with VC++7 in "compile as C source" mode both arguments are of type int.
sharptooth
@sharptooth You are right - debug information shows that printit() returns int and takes two ints as params. Thank you for valuable comment, I've corrected my answer.
qrdl