What happened to int main ()?

I can’t count the number of times I saw C code here and here on SO, which defines main as

int main() { ... 

When I compile it with

 gcc -ansi -pedantic -Wstrict-prototypes -Werror foo.c 

with an error

 foo.c:2: warning: function declaration isn't a prototype 

Why is this

 int main(void) 

Do you want the error to disappear?

+4
source share
3 answers

Since the definition

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

does not include a prototype; it does not indicate the number or type of parameters.

It:

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

contains a prototype.

With empty parentheses, you say that main accepts a fixed but unspecified number and type of arguments. With (void) you explicitly say that it does not accept any arguments.

On the first call:

 main(42); 

will not necessarily be diagnosed.

This goes back to the days leading up to ANSI before prototypes were introduced into the language, and most functions were defined with empty parentheses. Then it was completely legal to write:

 int foo(); int foo(n) int n; { /* ... */ } ... foo(42); 

When prototypes were added to the language (borrowed from C ++), it was necessary to preserve the old meaning of empty parentheses; the "new" (it was 1989) syntax (void) was added, so you can explicitly say that the function takes no arguments.

(C ++ has different rules, it does not allow the use of non-prototyped old-style functions, and empty parentheses mean that the function takes no arguments. C ++ allows the syntax (void) for compatibility with C, but it is usually not recommended.)

It is best to use (void) because it is more explicit. It is not clear that the form int main() even valid, but I have never seen a compiler that does not accept it.

+7
source

This is not a mistake - warns. The flag says it all: it expects you to take care of the arguments received by main (usually int argc, char **argv) .

+2
source

According to the gcc documentation, this is a warning when you added -Wstrict-prototypes because:

-Wstrict prototypes (C and Objective-C only)
Warn if function is declared or defined without specifying argument types . (The definition of an old-style function is permitted without warning if it is preceded by a declaration that indicates the types of arguments.)

But for you, this is an error due to -Werror :

-Werror
Prevent all warnings.

In general, it's wrong to define main() like this (regardless of what you saw here), C spec determines how main() should look in 5.1.2.2.1:

The function called when the program starts is called main. The implementation does not declare a prototype for this function. It is defined with an int return type and without Parameters:

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

or with two parameters (called argc and argv here, although any names can be used since they are local to the function in which they are declared):

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

+1
source

All Articles