How to cout the return value of the main function "main()"? I just want to check if the return value of main function is really "0" when it is successfully executed.
Thank you!
How to cout the return value of the main function "main()"? I just want to check if the return value of main function is really "0" when it is successfully executed.
Thank you!
Do you mean you want to test that the following returns 0?
int main() {
int rc = doSomething();
return rc;
}
You can do it like this:
int main() {
int rc = doSomething();
std::cout << rc << "\n"; // Just print it out before returning
return rc;
}
But it's better to check the return value in the shell from where you run your application:
On UNIX/Linux (in shell):
> ./my_app
> echo $?
0
On Windows (in command prompt):
> my_app.exe
> echo %ERRORLEVEL%
Note that in C++ you are not allowed to intercept the call to main()
or call it yourself.
3.6.1 Main function
The function
main
shall not be used within a program.
So you should not attempt to wrap the main()
call and print its return value. Even if that works, it would not be portable (not to mention you'd actually end up running your application twice).
You can use a unix command to check the return value of the previously executed command, in this case your c program.
echo $?
The shell variable $? is the return code of the previous command.
How to find the return value of last executed command in UNIX?
If you want to check the value within the code, just cout the value right before the return.
main
is special, mostly because you can't call it yourself. The value that it returns is passed back to the operating system, which does whatever is appropriate. The C++ standard can't dictate how the OS treats various return values, so it provides an abstraction: you can use return EXIT_SUCCESS
to indicate success, and you can use return EXIT_FAILURE
to indicate failure. (You can also use return 0
to mean return EXIT_SUCCESS
; the program's runtime system has to handle this correctly). The values of the macros EXIT_SUCCESS
and EXIT_FAILURE
are suitable for the OS that the program was compiled for. While 0
is the typical value for EXIT_SUCCESS
, it's certainly possible for an OS to require a different value, and EXIT_SUCCESS
will have the appropriate value for that OS. So even if you could check the value returned from main
it wouldn't tell you much, without also knowing what value the OS expects from a successful program.
Type the other function after main()
, then type main();
in that function
One problem though, main will be the first function to be called automatically. Although, i'm sure there is a way to fix it. This is how you call main or return main.
Hope this helps.
int main() {
int i = 5;
cout << i;
}
int second() {
main();
}
Welcome to Stack Overflow!
If it's 0, then it's 0. You are the one who specify the return value of your own function. If you are unsure, please add code and/or problem, which is bothering you.