What is the correct (most efficient) way to define the
main()
function in C and C++ — int main()
orvoid main()
— and why? If int main()
then return 1
or return 0
?There are numerous duplicates of this question, including:
- What are the valid signatures for C's
main()
function? - The return type of
main()
function - Difference between
void main()
andint main()
? main()
's signature in C++- What is the proper declaration of
main()
? — For C++, with a very good answer indeed. - Styles of
main()
functions in C - Return type of
main()
method in C int main()
vsvoid main()
in C
Related:
- C++ —
int main(int argc, char **argv)
- C++ —
int main(int argc, char *argv[])
- Is
char *envp[]
as a third argument tomain()
portable? - Must the
int main()
function return a value in all compilers? - Why is the type of the
main()
function in C and C++ left to the user to define? - Why does
int main(){}
compile?
Answers:-
The return value for
main
should indicate how the program exited. Normal exit is generally represented by a 0 return value from main
. Abnormal termination is usually signalled by a non-zero return but there is no standard for how non-zero codes are interpreted. Also as noted by others, void main()
is explicitly prohibited by the C++ standard and shouldn't be used. The valid C++ main
signatures are:int main()
and
int main(int argc, char* argv[])
which is equivalent to
int main(int argc, char** argv)
It's also worth noting that in C++,
int main()
can be left without a return value at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0 should be omitted or not is open to debate. The range of valid C program main signatures is much greater.Also, efficiency is not an issue with the
main
function. It can only be entered and left once (marking program start and termination) according to the C++ standard. For C, the case is different and re-entering main()
is allowed, but should probably be avoided.
0 comments:
Post a Comment