Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you omit the return type in main function? [duplicate]

Tags:

Are there some special rules with respect to the declaration of the main function?

According to ideone this is legal C++:

main()  // As opposed to int main()
{
   return 0;
}

On the other hand, normal functions do not seem to have the privilege to avoid the return type:

f(){} 

int main()
{
    return 0;
}

Gives the error:

prog.cpp:1:3: error: ISO C++ forbids declaration of 'f' with no type [-fpermissive] f(){} ^

Is the main function special in this case?

like image 445
Martin Drozdik Avatar asked Sep 30 '16 10:09

Martin Drozdik


People also ask

Does main need a return type?

Master C and Embedded C Programming- Learn as you go In C++ language, the main() function can be left without return value. By default, it will return zero.

Does a main function need a return statement?

In a main function, the return statement and expression are optional.

Can Main have void return type?

C++ does not allow main to have a void return type. The published C++ standard requires it to be int . Some C++ compilers allow you to use void , but that's not recommended.

Can return type of main function be double?

Yes. According to C standard, main() should return a int value.


2 Answers

Never omit main's return type, as it's non-standard!


wandbox example:

prog.cc:1:6: warning: ISO C++ forbids declaration of 'main' with no type [-Wpedantic] main()


From $3.6.1:

1 A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. — end note ] § 3.6.1 58

2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined

like image 72
Vittorio Romeo Avatar answered Oct 04 '22 14:10

Vittorio Romeo


No, it works because compilers support really old C, that allowed that.

like image 35
Andrzej Budzanowski Avatar answered Oct 04 '22 15:10

Andrzej Budzanowski