What Happens If Main() Does Not Return an Int Value

What happens if main() does not return an int value?

If main doesn't return int, then you have an ill-formed program and behavior is undefined. Anything can happen. Your program might crash, or it might run as though nothing were wrong at all.

Let's suppose main returned something other than int, and your compiler and linker allowed the program to be made. The caller doesn't know that, though. If the caller expects returned int values to be returned in the EAX (Intel) register, then that's what it will read to determine the return value of main. If your faulty main stored a float value there, then it will be interpreted as an int instead. (That doesn't mean it will get truncated. It means the bits making up the layout of a floating-point value will instead make up an int instead.) If your faulty main returned void, then it didn't store anything in the expected register, so the caller will get whatever value was previously stored in that register instead.

If your main returns some type that it expects to store someplace that the caller didn't' reserve memory for (such as a large struct), then it will end up overwriting something else, perhaps something important to the clean shutdown of the program, causing your program to crash.

Why does the main function work with no return value?

Normally it is not allowed for the control flow to reach the end of a non-void function without returning something. The main function is handled differently, as specified in the standard.

From http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2960.pdf:

§ 3.6.1/5

If control reaches the end of main without encountering a return
statement, the effect is that of executing return 0;

As for the rationale, I'm not sure, honestly. If someone knows, please add it to my answer or as a comment.

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.

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.".)

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.

Purpose of using a Main method that explicitly returns an int

If you rely on the void syntax returning a 0, then your program is only ever going to return a 0, which is by convention the status code for a successful execution. For many use cases, that may be fine, but the point of allowing your main method to explicitly return an int is that you can return different ints in different cases. For a non-trivial application, if you manually return different int values in meaningful contexts, you're going to get a lot more value out of that functionality than blindly returning a 0 in all termination scenarios.

Additionally, it seems like you're asking about why you should bother explicitly saying static int Main instead of static void Main if both will return an integer. Besides the above note about returning meaningful values, more broadly, if you want your method to return an integer, then it would make sense to utilize the explicit syntax rather than relying on fallback behavior, simply because doing the latter may be unknown or non-intuitive to someone else modifying or using your program. Look at your question the other way - if you wanted your main method to return an int, why wouldn't you use the syntax to do so explicitly? Does it make sense for a void method to return an int?



Related Topics



Leave a reply



Submit