Return a value

Why do you have to have a "return 0;"at the end of your function? I understand that every function has to return a value (except a void function), but what does that even mean? Why not use a void function in place of another function?

What's the difference between the following functions?

int main()
{
cout << "Hello World\n";
return 0;
}


void helloWorld ()
{
cout << "Hello World\n";
}





Thanks for your help!


Last edited on
That's just how c++ is implemented. It is implicit. You don't have to type return 0; in main C++ implicitly does that. Techinically, you save typing 1 character less ;)
If you're asking, "Why does the main function have to return something?", the answer is because the return value of the main function of your program is typically used to indicate error codes to be used by the operating system/host environment. For example, if you cancel an installer right in the middle of installing new software, the installer might return an error code to the operating system - if such an error code is returned on Windows, a prompt will appear asking whether or not the software installed correctly.

If you're asking, "Why do functions have to return things in the first place?", the answer is because it's useful.
It's very straightforward, for instance, to write a function which returns the sum of its arguments:

1
2
3
4
5
6
7
8
9
10
11
int sum(int a, int b) {
	return a + b;
}

int main() {

	int number = sum(1, 2);

	return 0;

}


If you still can't grasp the concept of return, I suggest you keep re-reading all the tutorials you can find. It's pretty fundamental considering that any expression "returns" something in some sense or another.
Topic archived. No new replies allowed.