raghu said:
i'm surprised at the output of the following code. compiled in turbo C
void main()
{
printf("%d",sizeof(printf());
}
the output was : 2
how come the output is 2? actually what is the property of sizeof()
and printf()?are there any return types for the two functions? hoping
for the positive responses.. thanks a lot in advance.
There should be no cause for surprise, no matter what
output is or is not produced. You should not be surprised
if the code makes demons fly out of your nose, because it
invokes undefined behavior not once, not twice, but thrice:
- The main() function is not `void'
- It is U.B. to call a variadic function like printf()
without a prototype in scope
- It is U.B. to pass a non-`int' to the "%d" specifier
(On some "exotic" systems where `size_t' is narrower
than `int' this might be all right, so I really should
say that whether the behavior is defined or undefined
is implementation-defined.)
.... and on top of all that, the fate of a newline-less "line"
at the end of a stream of output is implementation-defined.
(Three instances of U.B. and one of I.D.B., or possibly
two U.B. and two I.D.B. -- all in just four lines, two of
which consist only of braces. Is this density of errors --
a density of densness, one might say -- a candidate for the
Guinness Book? Sadly, I fear not.)
Here's a cleaned-up version:
#include <stdio.h> /* for printf() prototype */
int main(void) {
printf ("%d\n", /* note newline */
(int)sizeof printf()); /* note type coercion */
return 0; /* required in C90, optional in C99 */
}
Now, you may still be puzzled about the output of the
cleaned-up version of your bletcherous code. Much will become
clearer if you ponder two questions:
- What does the `sizeof' operator do with its argument?
- What type does the printf() function return?
Answer these, Grasshopper, and you will be on the path
to enlightenment -- but if you keep on writing code like the
sample you provided here, it means you're on the right path
but walking in the wrong direction.