user45797
user45797

Reputation: 3

In C++ return -1 does not return any error?

Should the super simple code below produce an error? Should it produce anything?

int main()
{
    return -1;
}

I am just starting to work through the 'C++ Primer' and supposedly from Exercise 1.2:

A return value of -1 is often treated as an indicator that the program failed. Recompile and rerun your program to see how your system treats a failure indicator from main.

It seems like my system treats a failure indicator as business as usual and it is driving me crazy!!!

I can return any number, positive or negative and there won't be an error. Only when I type in a string like 'return cisstupid;' I would (obviously) get an error. An hour of googling has not yielded anything and I have tried running the code with -Wpedantic, -Wall, -Werror (i.e. g++ -Wpedantic -o test test.cpp). The system is Windows 8.1 with mingw installed.

Upvotes: 0

Views: 1088

Answers (3)

OshoParth
OshoParth

Reputation: 1552

return keyword is used to return some value to the calling function by the function that has been called this return value can be almost anything the interpretation of the return value entirely depends on how the calling function has handled the return value.

int main()
{
    return -1;
}

Here you are simply returning a negative number using return whose interpretation can be handled in the calling function (here Operatin. This is a convention not a protocol or rule to treat this return value as an operational error for the program , depending on the calling system the value of return can effect the output ie. as CiaPan stated that there is much difference between the often and always words.

In Short the interpretation of return -1 depends on the calling System.

Upvotes: 1

nchen24
nchen24

Reputation: 502

Programs can complete with an error. I'm not sure what kind of shell you are using, but with a bash shell, you can type echo $? to get the return code of the last executed program.

To understand why this is, consider this: Most of the time, you do not want the entire system to come to a halt. You do, however, want to know that something went wrong. So it is common to call something, get the return value, then react appropriately, rather than let the entire thing blow up.

Upvotes: 0

David
David

Reputation: 4873

If you're on Windows, yes, returning anything is business as always. I'm not sure about other systems, but I've never heard of using a different return value in main to indicate something bad has happened to the user.

The actual use for return values is just as you know them, to get information back. The return value of main is used the same way. If you're in A.exe and call B.exe, then you can use main's return value to indicate whether or not B.exe ran successfully. However, where you're at now, you'll never do that, hence you just always return 0.

Upvotes: 0

Related Questions