Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does main() have to return an int? [duplicate]

Tags:

c++

In most cases int main() does not return anything, it doesn't even have to since no return would not give an error. So why does main have to return an int? Why is void main not possible?

EDIT: I meant, why is int main() the standard if there usually is no return?

like image 651
user2180680 Avatar asked May 17 '13 13:05

user2180680


People also ask

Why is main () an int?

The short answer, is because the C++ standard requires main() to return int . As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished.

Does a main function need a return statement?

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

Does main always have to return int C++?

Yes, main() must return int . The return value is passed back to the operating system, to indicate whether the program ran successfully: zero means success. However, you can leave the return statement out of main (and only main ) if you like; in that case, it will return zero.

What happens if I return 1 in main function?

return 1: A return 1 means that there is some error while executing the program, and it is not performing what it was intended to do.


2 Answers

Other programs may use the return code to determine whether the application executed successfully. Zero typically means successful execution.

like image 74
Matthew Avatar answered Oct 10 '22 21:10

Matthew


void is possible but non-standard. The returned int is meant to signify something for the caller.

like image 29
Alexander Kulyakhtin Avatar answered Oct 10 '22 21:10

Alexander Kulyakhtin