Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should main() return in C and C++?

What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why? And how about the arguments? 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() and int 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() vs void 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 to main() 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?
  • Legal definitions of main() in C++14?
like image 939
Joel Avatar asked Oct 15 '08 12:10

Joel


People also ask

What does main function return in C?

The return value of main() function shows how the program exited. The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value.

Does C main need a return?

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

Should main always return a value?

The main function is C always return an integer value and it goes as an exit code to the program which executed it.

Where does main function return its value in C?

In C/C++ language, the main() function can be left without return value. By default, it will return zero. Some compilers allow the usage of void main() .


1 Answers

The return value for main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not 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 is also worth noting that in C++, int main() can be left without a return-statement, 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.

Efficiency is not an issue with the main function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main() is allowed, but should be avoided.

like image 145
workmad3 Avatar answered Sep 19 '22 14:09

workmad3