2

I am currently reading what functions are in c++. It says that they are "artifacts that enable you to divide the content of your application into functional units that can be invoked in a sequence of your choosing.A function, when invoked, typically returns a value to the calling function."

It then goes on to say that main() is recognized by the compiler as the starting point of your c++ application and has to return an int (integer).

I don't know what is meant by 'has to return an integer'. From my (extremely limited experience) int main () is the start of your application. But what is meant by 'has to return an int'?. This is also intertwined with me not understanding 'typically returns a value to the calling function'

user14445
  • 187
  • 1
  • 7
  • Typically: `return 0;` – Wok Jul 26 '13 at 12:56
  • It means it can't return a `double`, or `char*` or `vector` or anything else that isn't exactly `int` and only `int`. – jrok Jul 26 '13 at 12:56
  • Answer: http://stackoverflow.com/a/204483/376454 – Wok Jul 26 '13 at 12:57
  • 1
    The value returned by `main` will be the value returned by your program to the operating system. It's supposed to be an integer value describing the [exit status](http://en.wikipedia.org/wiki/Exit_status). – zakinster Jul 26 '13 at 12:57
  • @jrok: Or anything that is convertible to `int` – David Rodríguez - dribeas Jul 26 '13 at 13:00
  • These links should help; http://www.eskimo.com/~scs/readings/voidmain.990301.html http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044841143&id=1043284376 http://users.aber.ac.uk/auj/voidmain.cgi – JNL Jul 26 '13 at 13:01
  • @DavidRodríguez-dribeas I meant the type in the declaration, not the type of the expression in return statement. – jrok Jul 26 '13 at 13:02

5 Answers5

9

Just like in mathematics, in C++ functions return values. All functions in C++ must specify exactly what type of value they return, and every function must return only one type of thing. In some cases, that "one type of thing" might be nothing, which is denoted in C++ with the keyword void.

Every function must declare what it returns. This is done via a function declaration. Here are several examples:

int foo();
void bar();
string baz();
int main();

4 function declarations. foo returns an int, bar returns nothing, baz returns a string (which is declared in the C++ Standard Library), and main returns an int.

Not only must every function declare what it returns, it must also return that type of thing. If your function returns void, then you can write:

void bar()
{
    return;
}

...or just do nothing:

void bar()
{
}

If your function returns anything other than void, then you have to have a return statement that returns that type of thing:

int foo()
{
  return 42;
}

If you declare a function to return one type of thing, but then try to return another type of thing, then either there must be a way to implicitly convert from whatever you're trying to convert to what the function is declared to return. If there is no possible implicit conversion, your program won't compile. Consider:

int foo()
{
  return "foobar rulez!";
}

Here, foo is declared to return an int, but I'm trying to return a string (not a string from the Standard Library, but an old C-style const char* string. `"foobar rulez!" here is called a string literal.)

It is possible to write code to provide the implicit conversion I mentioned earlier, but unless you know exactly why you want to do that it's better to not get mixed up in all that right now.


What do you do with the values that are returned from functions? Again, just like with mathematics, you can use those values somewhere else in your program.

#include <cstdlib>
#include <iostream>

int foo()
{
  return 42;
}

int main()
{
  int answer = foo();
  std::cout << "The answer to Life, the Universe and Everything is...\n"
    << answer << "!\n";
  return 0;
}

Obviously you can't do anything with the value that is returned from a function that returns void, because a function that returns void doesn't really return anything at all. But these kinds of functions are useful for doing stuff kind of on the side.

#include <cstdlib>
#include <iostream>

int theAnswer = 0;    

void DeepThought()
{
  theAnswer = 42;
}

int foo()
{
  return theAnswer;
}

int main()
{
  DeepThought();

  int answer = foo();
  std::cout << "The answer to Life, the Universe and Everything is...\n"
    << answer << "!\n";
  return 0;
}

OK, back to all this business with main.

main is a function in C++. There are a few things about main that make it special compared to other functions in C++, and two of those things are:

  1. Every program must have exactly one function called main() (in global scope).
  2. That function must return an int

There is one more thing about main that's a little special and possibly confusing. You don't actually have to write a return statement in main*, even though it is declared to return an int. Consider:

int main()
{
}

Note that there's no return statement here. That is legal and valid in C++ for main, but main is the only function where this is allowed. All other functions must have an explicit return statement if they don't return void.

So what about the return value from main()? When you run a program on an Windows or Linux computer, the program returns a value to the operating system. What that value means depends on the program, but in general a value of 0 means that the program worked without any problems. A value other than 0 often means that the program didn't work, and the exact value is actually a code for what went wrong.

Scripts and other programs can use these return values to decide what to do next. For example, if you wrote a program to rename an MP3 file based on the Artist and track Number, then your program might return 0 if it worked, 1 if it couldn't figure out the Artist, and 2 if it couldn't figure out the Track Number. You can call this function in a script that renames and then moves files. If you want your script to quit if there was an error renaming the file, then it can check these return values to see if it worked or not.


  • no explicit return statement in main: In cases where main does not have an explicit return, it is defined to return the value 0.
John Dibling
  • 94,084
  • 27
  • 171
  • 303
5

Although it may appear so when you are programming in C or C++, main is not actually the "first thing" that happens. Typically, somewhere in the guts of the C or C++ runtime library is a call to main, which starts your program. When your program is finished and returns from main, it will return a value (in C++, if you don't specify something, the compiler will automatically add return 0), and this return value is used to signal "the success" of the program.

In Unix/Linux etc, this is used as $?, so you can echo $? after running a program to see what the "result" was - 0 means "went well", other values are used for "failure". In windows, there is a ERRORLEVEL variable in batch scripts, etc, that can be used to see the result of the last command.

Edit: If your code calls another program, e.g. through CreatProcess in Windows, or fork()/exec() in a Unix style OS (or the C runtime functions spawn and siblings in almost any OS), the return value from main is the new process finishes, and made available for the owning process. End Edit.

Since, even in C++, main is a "C" style function, if you change the return type, it still has the same name, so the linker/compiler can't "detect" that it's got the wrong return type, and some weird stuff will happen if you declare void main(), std::string main() or float main() or something other than int main() - it will still compile, but what happens in the code calling main will be undefined behaviour - this means "almost anything can happen".

Mats Petersson
  • 119,687
  • 13
  • 121
  • 204
  • But to whom is this value returned? Is it to me, and if so; where can I see it? – user14445 Jul 26 '13 at 13:02
  • It is returned to the code in the C or C++ runtime code that called `main`. Typically, it is then passed to the OS to be used as the exitcode, e.g. `_exit()` in Unix/Linux oir `ExitProcess()` in Windows, and from there, it appears, as I explained above, in the `$?` or `ERRORLEVEL` variables in the command line interpreter. – Mats Petersson Jul 26 '13 at 13:05
  • It's evident even from the C++ level that `main` isn't the first and the last thing. Construction of static-duration objects happens before entering `main` and destruction happens after exiting `main`. BTW that is sort of a gray area and it's better to avoid doing anything fancy during those two periods (and more specifically it's important to avoid doing anything that can fail: debugging before `main` starts and after `main` ends can be a nightmare). – 6502 Jul 26 '13 at 13:05
  • @6502: Yes, of course, it's clear when you understand how those things work - but a s beginner programmer, that may not be so obvious [it just happens by magic, sort of...] – Mats Petersson Jul 26 '13 at 13:13
0

Yes, main should always returns an int, this can be used to show if the program runs successfully, usually 0 represents sucess, a non-zero value represents some kind of failure.

For example, in Linux, you can call your program in a bash script, and in this script, run different commands on the return status of your program.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
  • And where will the 'int' be returned to? Where can you see this integer? – user14445 Jul 26 '13 at 12:59
  • 1
    @user14445 The application that invoked your application can see this integer. If that application was a shell you can then see that exit status in the `$?` variable. – sepp2k Jul 26 '13 at 13:04
  • 1
    @user14445: To the process that ran the program. On most Unixy shells, you can use `echo $?` to see the exit status of the last program you ran. – Mike Seymour Jul 26 '13 at 13:04
0

It means, in the signature of main() the return type is int:

int main();
int main(int argc, char const *argv[]);

Now what value you would return from main(), is the question. Well, the return value is actually exit status which indicates to the runtime whether the main() executes sucessfully or unsuccessfully.

In Linux, I usually return EXIT_SUCCESS or EXIT_FAILURE depending on the cases. These are macros defined by <cstdlib>.

int main()
{
     //code
     if ( some failure condition ) 
           return EXIT_FAILURE;

     //code

     return EXIT_SUCCESS;
}

As per the doc:

#define EXIT_SUCCESS /*implementation defined*/
#define EXIT_FAILURE /*implementation defined*/

The EXIT_SUCCESS and EXIT_FAILURE macros expand into an integral expression and indicate program execution status.

  Constant                   Explanation
  EXIT_SUCCESS   successful execution of a program
  EXIT_FAILURE   unsuccessful execution of a program
Nawaz
  • 327,095
  • 105
  • 629
  • 812
0

This is how you report back to the operating system the exit status of the program, whether it ran successfully or not. For example in Linux you can use the following command:

echo $?

to obtain the the exit status of the program that ran previously.

Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682