Reputation: 572
So I'm completely new to C++ but know already a lot about Java.
I'm currently watching thenewboston's tutorial and he said that if you return 0 the computer knows the program works successfully.
Well, my question is now: Does this affect functions? If I want to return a calculated number and it's surprisingly 0, do I get 0 back or does the function send nothing back?
Upvotes: 0
Views: 2594
Reputation: 35970
Returning zero is a convention, especially in Unix world. If a program (so it's main() function) returns zero, it means it finished successfully. Other values can (not neccesarily though) mean an error. You can see sysexits.h
for a list of common return codes.
Also, if you miss return statement, main() will still (implicitly) return zero (valid for C++). It is defined in C++ standard, 3.6.1 point 5:
If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;
In shell, ex. Bash, you can check what value has been returned from main() by looking at $?
variable, on example:
$ g++ prog.cpp
$ ./a.out
$ echo $?
0
For functions other than main() you should remember that zero, in comparison, is a boolean false, so returning zero may not be intepreted as a success (or true). But the return value can be anything and, in general, it does not have any special meaning, so returning zero is okay.
Upvotes: 5
Reputation: 15916
you return 0 the computer knows the program works successfully.
This is specific to the main function. Any other function can return whatever they want. Main is special in that it is the entry point for your program and also the exit point. When your program starts main is called when it only ends once main returns. Watching the return code of the main function is I think a practice that is going out of style these days but you still see a lot of code returning things like -1 when an error occurs. Who's watching that error code? The OS most of the time.
Upvotes: 8
Reputation: 10730
Returning 0 in the main
function is the only one that has any special meaning. It's generally so that the OS can understand the program was successful, it's not particularly interesting insofar as C++ internals itself.
Upvotes: 4