Vijay Kumar R Zanvar said:
Why the following program gives two different
answers? -
Short answer: because C is not Pascal.
Long answer:
printf ( "%u\n", sizeof ( main ) );
This asks for the size of the main function, which is actually illegal:
# 6.5.3.4 The sizeof operator
# Constraints
# 1 The sizeof operator shall not be applied to an expression that has
# function type
Since your compiler apparently decided to compile thr program anyway,
this constraint violation invokes undefined behaviour, and may give any
answer whatsoever. In principle, anything which happens after this point
could be completely random.
printf ( "%u\n", sizeof ( main () ) );
This asks for the size of the value returned by evaluating main(). Since
main() returns int (and you've correctly defined it as doing so), that
is equal to sizeof (int). Note, btw, that main() isn't evaluated, since
its size can be determined without doing so (unlike its value).
Note also that you are invoking undefined behaviour in both printf()
calls, because you don't know that size_t is equivalent to unsigned int.
Either cast both sizeofs to (unsigned int), so it corresponds to the
printf() specifier %u, or, if you use C99, change the %u to %zu.
GCC 3.3.2 (Windows XP) gives the following o/p:
1
4
Apparently, your compiler has decided to give all functions a size of 1,
and int is four bytes large on your implementation.
Richard