What Should Main() Return in C and C++

What should main() return in C and C++?

The return value for main indicates how the program exited. Normal exit is represented by a 0 return value from main. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main() is prohibited by the C++ standard and should not be used. The valid C++ main signatures are:

int main()

and

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

which is equivalent to

int main(int argc, char** argv)

It is also worth noting that in C++, int main() can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0; should be omitted or not is open to debate. The range of valid C program main signatures is much greater.

Efficiency is not an issue with the main function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main() is allowed, but should be avoided.

Need help understanding return value of int main() in C++ coding example

It seems the confusion here is not about the main function primarily, so let's step away from main for a moment.

Printing a value and returning a value are fundamentally two different things that really don't have anything to do with one another. The confusing part is we often use the word "output" to mean one of several different things.

Let's start with understanding what a return value is by itself. So hopefully you know that functions can be called from inside other functions and serve as a way to organize the functionality within a program. Let's look at a very simple example:

int getDoubled(int x)
{
return 2 * x;
}

Here we've defined a simple function with the name getDoubled and it expects, as an argument, a single integer and returns a single integer. And we can see from the code that the integer returned is x, the input argument, multiplied by 2.

Now that we have a function we can call it from somewhere else:

int y = getDoubled(3);

Here we've called the function by writing its name followed by a parameter list. This means the code inside the function will be run and the expression in its return statement will be the value that it acts like. In this case that means y is assigned the value 6, because getDoubled(3) evaluates to its return value of 6.

Notice this has nothing to do with printing the value 6 to the screen, the return type and value of a function in C++ is only for determining the value the function call represents in an expression. Consider this now:

int y = getDoubled(getDoubled(3));

Now y will be assigned the value 12 because the inner getDoubled call returns 6, which is passed as the parameter to the outer getDoubled call which then returns 12.

Since function calls are just expressions they can be used anywhere an expression is expected, like in an if statement:

if (getDoubled(y) < z)  { /* ... */ }

In fact, we can even use the bool return type to write functions we might call directly in an if statment:

bool isLess(int x, int y)
{
return x < y;
}

So now we could write something like:

if (isLess(z, 5)) { /* ... */ }

Admittedly doing this is pretty pointless since you could also just write z < 5 in there. This is just to illustrate how this works without getting bogged down in irrelevant details.

So the return type describes the type of value that a function call will evaluate to.

Now, with all that said, main is actually very special. It's not an ordinary function, because you're actually not permitted to call main yourself and you're even allowed to omit its return statement. The reason for this is that the operating system, which is going to run your program, needs some entry point to start running from.

Unlike Python, C++ doesn't allow "executable" code at the top level of a program, it only allows definitions and declarations (there's some wiggle-room here for initializing static variables and the like, but we'll ignore that for now). My point here is you can't just write this as a program in a cpp file:

std::cout << "Hello world!\n";

C++ requires that these sort of statements only appear inside functions. So when the operating system goes to execute your program, where does it start? This is what the purpose of main is. It marks the entry point for your program. It's as if the operating system calls that main function whenever your program is run by a user.

This is in contrast to Python where the entry point of your program is simply the script file that was invoked. There is still technically a main, but that's inside the python executable itself and you don't have to worry about it there.

As other answers point out, the return value of the main function is purely for the purposes of the operating system to understand whether your program completed successfully or failed for some reason. And for that purpose it uses an int.

Okay, so with that out of the way, what's the deal with printing and cout? Well, this is another part of the interface between your program and the operating system. Your program actually has what are called standard streams. Usually there's 3 of them: standard output, standard input, and standard error. These are all provided in C++ as cout, cin, and cerr, respectively.

When you write to cout you're putting data into the standard output stream of your program. Any part of your program can do that. That standard output stream usually prints to the console if you've created a console application. But operating systems usually let you send that output stream to other places, like a file, or even connecting it to the input of another program.

One way to think of it is like a special file that you can write to (and likewise for cin that's a different special file that you can read from). It's one way to get data out of your program and up to where the user can see it, but it's entirely different mechanism to returning from a function.

The return type of main() function [duplicate]

The C standard (ISO/IEC 9899:2011) says:

5.1.2.2.1 Program startup


1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent;10) or in some other implementation-defined manner.

10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char **argv, and so on.

Thus, the only portable declaration for main() has a return type of int. If MSVC defines that void is permitted ('or in some other implementation-defined manner'), so be it, but do not expect the code to be portable. The old versions of the Microsoft compilers (up to and including MSVC 2005) do not permit void main(): see the documentation at main: Program startup and The main Function and Program Execution. However, MSVC 2008 and later are documented to allow void main(): see main: Program Startup. The three-argument form of main() is noted as a common extension in Appendix J:

J.5 Common extensions


The following extensions are widely used in many systems, but are not portable to all
implementations. The inclusion of any extension that may cause a strictly conforming
program to become invalid renders an implementation nonconforming. Examples of such
extensions are new keywords, extra library functions declared in standard headers, or
predefined macros with names that do not begin with an underscore.

J.5.1 Environment arguments


In a hosted environment, the main function receives a third argument, char *envp[],
that points to a null-terminated array of pointers to char, each of which points to a string
that provides information about the environment for this execution of the program
(5.1.2.2.1).


The value returned from main() is transmitted to the 'environment' in an implementation-defined way.

5.1.2.2.3 Program termination


1 If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;11) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.

11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.

Note that 0 is mandated as 'success'. You can use EXIT_FAILURE and EXIT_SUCCESS from <stdlib.h> if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.

7.22.4.4 The exit function


¶5 Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Why return 0 from main() in a C program? [duplicate]

It returns the 0 to OS to tell the OS that your program executed successfully.

Is It Necessary to Return a Value in Main()?

The C99 standard says: (§5.1.2.2.1 Program startup)

The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

So in a hosted environment, int is the only valid, standard return type. Implementations can define other entry points though.

Note that section §5.1.2.2.3 Program Termination has this:

If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument; reaching the } that terminates the
main function returns a value of 0
. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.

So you omitting a return from main is legal in C99, as long as your main returns an int.

(But previous versions of the C standard didn't have that exception for main - returning no value (or reaching the final } without a return statement) causes "the termination status returned to the host environment [to be] undefined.".)

Return in C and C++ [duplicate]

The return value from the main function is the exit value of the program. The process that calls your program can retrieve this exit value.

First a shell example:

./myprogram
exitvalue=$?
echo exitvalue = $exitvalue

And this will print 0 for the first program and 45 for the third. The second program will probably print 255 because the exit status is on most operating systems expected to be between 0 and 255.

Why does main() have to return an int? [duplicate]

Other programs may use the return code to determine whether the application executed successfully. Zero typically means successful execution.



Related Topics



Leave a reply



Submit