Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C: Difference between main() and int main () [duplicate]

Tags:

c

Possible Duplicate:
difference between main(void) and main() in c

I know this is super basic and some other threads already talked about similar questions. But I have a book (Absolute Beginners Guide to C) where all the code is written within the function main(). The int is always left out. How is that possible to run? Is that ok with maybe an older version of stdio.h?
Here is the sample code:

#include <stdio.h>

main()  // not int main()
{
printf("This is it\n");
return 0;
}
like image 379
Martin Avatar asked Nov 24 '12 17:11

Martin


3 Answers

I think the c89 standard will allow main() but c99 and above won't . You have to use int main() otherwise .

like image 73
Deepankar Bajpeyi Avatar answered Oct 26 '22 23:10

Deepankar Bajpeyi


main() works but is confusing, in C the main function always returns an int, to specify exit status, so the correct syntax is int main(), but if you do not bother to set the exit status then main() is enough, but the good C books will always have int main().

like image 23
Nelson Avatar answered Oct 27 '22 00:10

Nelson


These kind of questions are highly standard-version dependent, so a general answer doesn't make much sense.

From a C89 draft (correct me if official C89 Standard is different, it's not freely avalaible):

The function called at program startup is named main. The implementation declares no prototype for this function. It can be defined with no parameters:

int main(void) { /*...*/ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /*...*/ }

C99 and C11 standard say the same but they add something at the and:

[...]

or equivalent;[9] or in some other implementation-defined manner.

[9] Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on.

In general things that are not defined from the standard leads to undefined behavior, so that code is UB in C89/C90, and it could be valid in C99 and C11, but that's implementation-defined.

P. S.: as you can see, you should also add void in the parameters list, without it the behavior is defined as above.

like image 28
effeffe Avatar answered Oct 26 '22 23:10

effeffe