user7532121
user7532121

Reputation:

Program Runs Even Though I Return -1?

I am running this very simple c++ code:

    int main()
{
    return -1;
}

But when I compile it with g++ and run it (on ubuntu 14.04) it goes through and I get no errors. The book that I am reading, "C++ Primer" says that I should receive an error, so I was wondering if someone could show me what I am doing wrong.

Upvotes: 0

Views: 108

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263237

Your program runs normally, then returns a status of -1 to the environment. If you don't look at that status, you're not going to see any indication of an error.

If you're running from the bash shell, you can do something like:

if ./my_program ; then
    echo Success
else
    echo Failure
fi

or, on one line:

if ./my_program ; then echo Success ; else echo Failure ; fi

or, if you want to be obscure:

./my_program && echo Success || echo Failure

More simply:

./my_program
echo $?

Incidentally, returning a status of -1 is not a portable way to indicate failure. I suggest adding #include <cstdlib> to the top of your program and using return EXIT_FAILURE;. (The value of EXIT_FAILURE is typically 1, but it will be whatever it needs to be to denote failure on the system you're using.)

Upvotes: 2

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

The return value of main is what's called an exit code. If you run your program from a shell (such as bash on a Unix system or the CMD on Windows), you can examine the exit code. By convention, nonzero exit codes usually imply that something erroneous happened. For instance, your g++ compiler outputs a nonzero exit code if there's a compile error and 0 if everything goes correctly.

Since you said you're on Ubuntu, I assume you're using either bash or dash to run this program. Try running the program and then do echo $? after running the program. You should see the exit code your program returned.

Upvotes: 1

templatetypedef
templatetypedef

Reputation: 372784

The code that you've written here is perfectly legal C++. The program runs and then signals an exit code of -1. On some operating systems, if a program terminates with a nonzero exit code, the OS will report an error to the user indicating that something weird happened. On Ubuntu, though, programs that terminate with nonzero exit codes don't trigger an explicit error message, so what you're seeing is the expected behavior.

Upvotes: 1

Related Questions