What does a return 0 do?

I just know return 0 can exit the program in main function.
but how about in other member function?
Is it just kill the member function, or it kill the whole program?
All functions, except void functions, returns a value so that is what the return statement is used for. The return statement always exits the current function, but zero is just one of all possible values and the meaning depends on the function.

If you use the std::string::compare function, a return value of zero means that the two strings are equal:
http://www.cplusplus.com/reference/string/string/compare/

If you use the std::vector::size, a return value of zero means that the vector is empty:
http://www.cplusplus.com/reference/vector/vector/size/

Some functions can't return zero because the return type of the function is not numeric. A function that returns a vector can't possibly return zero because zero is not a vector, and can not be implicit converted into one.
I just know return 0 can exit the program in main function.
but how about in other member function?
Is it just kill the member function, or it kill the whole program?


The return 0-meaning in the main-function is, that the programm executed successfully.
Last edited on
The return 0 doesn't exit the program, the program exits because the main function has reached it's end.

You can return 0 (or another value) to exit from main() before the end!?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main(int argc, char* argv[]) {
    if(2 != argc) {
        std::cout << "Need a single program argument!\n";
        return 1; // exit here if no command line arg is provided
    }

    std::cout << "Hello \"" << argv[1] << "\"\n";

    return 0; // exit at end of function
}


Andy
Last edited on
Holy shit, what the fuck, of course the return statement ends the function...
What was I thinking? I think nothing at all...

return 0 ends the function and returns the value 0 to the parent function call
Last edited on
From my understanding, Return 0 basicly means your program executed correctly. If it's stopped in the middle (Because of some random error), it'll probably be left with "return 83" or some other number along those lines.
Every function returns to its point of call when it finishes its work. If its return-type is not void, then it must return a value. Here the operating system calls the main function, and main must return an integer to the operating system. But for member functions, main or some other functions call them. So, member functions return value to that function by which it is called.

The exit(int) function can be used to terminate the program from any place, and the value sent as argument returned to the OS.
*must include cstdlib
Topic archived. No new replies allowed.