venkat said:
I have written a program
void main()
{
printf("%d %d\n", sizeof main, sizeof(main()));
}
in this program the output is 1 and 4,
as i understood from the books, function name represents the address
of the function. i thought sizeof main should give 4 , and i don't
know why sizeof(main()) is giving 4, Can some one please explain what
the former one does and what the later one do?. Why is this behavior?
The correct declaration is "int main(void)"; your compiler might
happen to allow "void main()", but it's non-standard and non-portable.
Writing non-standard code for the sake of avoiding a return statement
isn't worth it; just add a "return 0;" at the end. (The "return 0;"
might not be necessary, but it can't hurt.)
Since you call printf(), you need to add "#include <stdio.h>". This
is another of those things that's mandatory, but your compiler might
not be friendly enough to warn you about it.
It's illegal (a constraint violation, requiring a diagnostic) to apply
sizeof to a function name. It's also illegal to apply sizeof to an
expression of type void (you declared main() to return void, so the
expression main() is of type void). Your compiler may be allowing
these applications of sizeof as a non-portable extension. (gcc has
such an extension, but the output you're seeing is inconsistent with
the way gcc does this.)
printf's "%d" format expects an int argument; sizeof yields a value of
type size_t. If the rest of the program weren't incorrect, you could
avoid that problem by casting the arguments to type int.
Here's a corrected version of your program:
#include <stdio.h>
int main(void)
{
printf("%d %d\n", (int)sizeof &main, (int)sizeof main());
return 0;
}
This will print two numbers, the size in bytes of a function pointer
and the size in bytes of an int. I get "4 4" on one system, "8 4" on
another; there are other possibilities.
Here's an exercise for you. Read your compiler's documentation and
find out how to enable warning messages. Using your program as you
posted it, errors and all, figure out how to make your compiler warn
you about *all* the errors I've pointed out. It might not be able to
warn about the mismatch in the printf format, but it should be able to
diagnose the other problems. Once you've found the right set of
options, develop the habit of using them whenever you use the
compiler, and correct any problems it warns you about. And remember
that fixing your code so it doesn't produce any warnings is the only
*beginning* of writing correct code.