// main is a function, so it has a return value like any other function.
int main()
{
if (true)
// When main returns, the program closes.
return 0;
elsereturn 1;
}
@manudo
OK. Now I understand it, but can I put return 0; as many times I want?
Do return 1; change the result of am algorithm?
You may use as many return statements as you want. The return statement does not change algorithms. It sets the point of exiting of a function and if the function is declared such a way that it shall return a value it also sets the return value.
return 0; alone is ambiguous. Depending on where you put it, it may or may not end your program. Take this for example.
1 2 3 4 5 6 7 8 9 10 11
int foo()
{
return 0;
}
int main(int argc, char **argv)
{
int myreturn= foo(); //even though foo returns 0, the program resumes
return myreturn; //program exits when main returns
}
Alternatively, if you -do- want to return from foo(), you can use exit(0); the exit() function can be found in the stdlib.h
BTW, exit() does not do any resource cleanup. If you have any important RAII to handle, you need to do that first.
Partially correct. On Unix-like systems it *does* close the file/socket descriptors, including stdin, stdout and stderr. The system also releases all allocated memory for you, closes memory mapped files, etc. So there is no need to worry about any system-wide resource leak. However, it doesn't flush any buffers before that, so if you have some buffered, but not yet flushed to disk data, you can lose them.
If you don't want to do any resource cleanup, use _exit instead of exit, but that is usable only if you are using e.g. fork or vfork.
Yes, I should have made that clear. Using exit(0) is very much like just crashing your program and having the OS clean up. This can lead to loss of data and, in more advanced applications, some other unfriendly screw-ups.