3

In the program below, where is the value of return 0 stored and what does it actually mean?

#include <iostream.h>

int main()
{
  cout<<"Hello World";
  return 0;
}
Niall
  • 28,102
  • 9
  • 90
  • 124
  • Depends on the operating system. – 101010 Jul 28 '16 at 08:42
  • 1
    The return value informs the hosting environment of the success status of your program. The only two values you can return portably are `EXIT_SUCCESS` or `EXIT_FAILURE`; the former has the same effect as returning `0`. Different platforms may support a wider variety of status values (e.g. Posix allows 8 bits worth of status). – Kerrek SB Jul 28 '16 at 08:47

3 Answers3

3

The return value of main() is typically the return value of the process (e.g. if it was called from the command line). Its exact storage location and the transfer mechanism back to the calling shell (or parent process) is defined by the platform being targeted.

A return of 0 (EXIT_SUCCESS) typically means the program completed without error. Non-zero values in turn indicate an error - your program would define what the exact meaning for each value would be.

Niall
  • 28,102
  • 9
  • 90
  • 124
1

The return value of main is used as the exit status of the process.

Let wikipedia describe what exit status means:

The exit status or return code of a process in computer programming is a small number passed from a child process (or callee) to a parent process (or caller) when it has finished executing a specific procedure or delegated task.

So, you might say that the return value is stored in the memory of the parent process.


The value in the standard macro EXIT_SUCCESS (defined by header <cstdlib>) indicates that the process was successful, while the EXIT_FAILURE value indicates failure.

On POSIX systems (and every other system that I've used), 0 indicates success, and non-zero indicates failure.

eerorika
  • 181,943
  • 10
  • 144
  • 256
0

It's not really defined by the language. Most commonly, it's stored in the EAX register in the x86 architecture. The control flow goes back to the process that called main() and it can do whatever it wants with it.

The most common meaning I see is zero for normal execution (success), and one for generic error, but each value could mean something specific to the program. I have never built a program that return anything meaningfull through the int from main, but say you create a program that adds two numbers, well, the meaning of the return is the sum of the two numbers, think of main as just a function, the one from which your program starts.

Kahler
  • 1,060
  • 5
  • 22