So I'm completely new to C++ but know already a lot about Java.
I'm currently watching thenewboston's tutorial and he said that if you return 0 the computer knows the program works successfully.
Well, my question is now: Does this affect functions? If I want to return a calculated number and it's surprisingly 0, do I get 0 back or does the function send nothing back?
you return 0 the computer knows the program works successfully.
This is specific to the main function. Any other function can return whatever they want. Main is special in that it is the entry point for your program and also the exit point. When your program starts main is called when it only ends once main returns. Watching the return code of the main function is I think a practice that is going out of style these days but you still see a lot of code returning things like -1 when an error occurs. Who's watching that error code? The OS most of the time.
Returning zero is a convention, especially in Unix world. If a program (so it's main() function) returns zero, it means it finished successfully. Other values can (not neccesarily though) mean an error. You can see sysexits.h for a list of common return codes.
Also, if you miss return statement, main() will still (implicitly) return zero (valid for C++). It is defined in C++ standard, 3.6.1 point 5:
If control reaches the end of main without encountering a return
statement, the effect is that of executing return 0;
In shell, ex. Bash, you can check what value has been returned from main() by looking at $? variable, on example:
$ g++ prog.cpp
$ ./a.out
$ echo $?
0
For functions other than main() you should remember that zero, in comparison, is a boolean false, so returning zero may not be intepreted as a success (or true). But the return value can be anything and, in general, it does not have any special meaning, so returning zero is okay.
Returning 0 in the main function is the only one that has any special meaning. It's generally so that the OS can understand the program was successful, it's not particularly interesting insofar as C++ internals itself.
Related
For context, the language I've been using to teach myself to code is Python. Now I'm trying to learn C++ to broaden my coding literacy, but I'm having trouble understanding how functions are returning values.
I've been reading the following documentation:
https://www.cplusplus.com/doc/tutorial/program_structure/
Perhaps I need a better understanding of returning a value vs outputting something, but what is confusing me about the first program structure exercise is that it starts off with the classic "Hello world" example, which is obviously a string. However, the "int main()" is expecting an integer, not a string, right? So wouldn't there be some sort of error that would prevent the program from compiling?
main returns int. Nothing else.
There are three portable return values from main: EXIT_FAILURE, EXIT_SUCCESS, and 0. Returning EXIT_SUCCESS or 0 returns an implementation-specific value that the OS will interpret as successful execution. Returning EXIT_FAILURE returns an implementation-specific value that the OS will interpret as failed execution. You get those macros from <cstdlib> or from <stdlib.h>.
Most of the time the value doesn't matter; it's simply ignored. But when you run a script through the OS, sometimes it matters whether a particular program succeeded, and then you write code in the script to check the value that the program returned. A simple example (well, simple for a shell script, but still somewhat cryptic):
./my_program
if [ $? -eq 0 ];
then
echo "Succeeded"
else
echo "Failed"
fi
Here, $? is the result of the previous command. Since the previous command was ./my_program, if the program ran successfully $? will be 0, and if not, it will be some other value.
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 main() function has an an int return code on the most operating system environments. The return code is the program exit code. A value of 0 means no error, other values are mostly interpreted as errors.
However, on an OS less embedded applications (bare metal) the main function never returns and therefore the function is declared as void main().
I've just started programming and I've come to hear the standard beginner's definition of "the use of the return value in main" a lot, but it does not get to the point I am trying to understand. So, yes a return value 0 for 'int main' for example signifies that the programme running was successful and since main is of int datatype, 0 reflects this.
BUT what is the point of this? Won't the computer already know that the code was successful or not? Surely, we could write a flawed code and then return 0, and by that logic, we (the programmers) are saying this code is correct but the compiler actually executes the programme and if it's wrong/flawed it simply cannot operate on it.
Please use explanations that a beginner could understand.
The return code of your program ain't about crashing, its about a functional kind of failure.
For example, the program grep defines exit/failure code 0 as successfully found and 1 as not found. While value 2 gets used for invalid input.
Within scripting, this can be used for some automated logic without the user needing a user to interpret the results.
As you are a beginner, I would recommend to always return zero as you are focusing on how to learn the language. Looking into how applications can connect to each other via exit codes is adding unneeded distraction/complexity.
A program can fail, because some expectations are not met.
For example, a program which count the number of lines in files passed as arguments to main would fail when one of the arguments is not a valid file name, or if, for some reasons, that file could not be opened. And if you code such a program, you'll need to explicitly add some program logic (that is, several or many source code lines) for that. A good programmer don't allow his program to crash (even with wrong or missing input or arguments).
A simple program which copies a source file into a destination requires two arguments. If main is not given two arguments, it should fail. If the first argument does not name a valid and accessible file, the program should also fail. If the copy could not be achieved because some disk is full, that program should also fail.
The return from main is, in practice, not some arbitrary integer. On Linux and many POSIX systems, it should be some integer between 0 and 255 (with 0 meaning "successful execution", and other exit values are for failures). See exit(3) & waitpid(2) for more.
By some convention (which you need to document) the failure codes (in practice there are few of them, usually less than a dozen and quite often 0 -named EXIT_SUCCESS- on success and 1 -named EXIT_FAILURE- on failure) could tell about the failure reason. See for examples the documentation of tar(1), coreutils programs, grep(1), etc.
BSD unixes define some conventions in sysexits (but Linux programs generally don't use that).
Shell scripts can easily test and handle the exit code.
Read also about the Unix philosophy. Successful command-line programs (e.g. cp(1)) could often be silent. Error messages would go (by convention) to stderr.
As you would learn more about C programming, you'll understand that conventions matter a big lot (and it is important to document them). Study also the source code of some existing free software programs, e.g. on github.
Remember that you don't write code mostly for the computer, but also -and mostly- for the person (perhaps you in a few months, perhaps some future developer working at your company, when you'll be a professional developer) which would have to improve your code....
The return value from main indicates if something worked in a "business" sense, not in a "technical" sense. If the program has a technical flaw, main probably won't return at all, as the program will probably have crashed, or the return value will be meaningless, due to undefined behaviour.
The return value is used in things like search programs to indicate if something the program was interested in was found or not. The computer can't know what to return in these sorts of cases, as it has no understanding of the semantics of the program.
The return value of main, which becomes the exit code of the process once it's done running, is not related to whether the code is correct C++, but whether it has executed correctly from the point of view of its semantics (its business logic, let's say).
While the program exists as C++ source code, returning from main is an instruction like any other. Having return 0; in main will not affect whether your program is a valid C++ program, and will not fix e.g. syntax errors. While being compiled, it's totally irrelevant w.r.t. correctness.
The return value of main comes into play when the compiled program actually runs (already in binary form).
That is, when you're executing e.g. gcc ... -o myapp, the return value of main does not come into play (indeed, it doesn't even exist). But when you're then executing ./myapp, its process exit code (which is used by e.g. shell) is what gets set by the return value of main.
For example, the unix if command tests whether its argument returned 0 or non-0:
if ./myapp; then
echo "Success"
fi
Whether the above shell script echoes Success or not depends on whether the process exit code of myapp was 0 or not, in other words, whether its main function returned 0 or not.
The Windows-world equivalent of such a check would be:
myapp.exe
if errorlevel 1 goto bad
echo "Success"
bad:
One common convention is to have a process exit code of 0 on success, 1 when the program couldn't complete its task (e.g. it was asked to remove a file which doesn't exist), and 2 when it was invoked incorrectly (e.g. it was given a command-line option it doesn't understand). These are the values main returns.
Should the super simple code below produce an error? Should it produce anything?
int main()
{
return -1;
}
I am just starting to work through the 'C++ Primer' and supposedly from Exercise 1.2:
A return value of -1 is often treated as an indicator that the program failed. Recompile and rerun your program to see how your system treats a failure indicator from main.
It seems like my system treats a failure indicator as business as usual and it is driving me crazy!!!
I can return any number, positive or negative and there won't be an error. Only when I type in a string like 'return cisstupid;' I would (obviously) get an error. An hour of googling has not yielded anything and I have tried running the code with -Wpedantic, -Wall, -Werror (i.e. g++ -Wpedantic -o test test.cpp). The system is Windows 8.1 with mingw installed.
return keyword is used to return some value to the calling function by the function that has been called this return value can be almost anything the interpretation of the return value entirely depends on how the calling function has handled the return value.
int main()
{
return -1;
}
Here you are simply returning a negative number using return whose interpretation can be handled in the calling function (here Operatin.
This is a convention not a protocol or rule to treat this return value as an operational error for the program , depending on the calling system the value of return can effect the output ie. as CiaPan stated that there is much difference between the often and always words.
In Short the interpretation of return -1 depends on the calling System.
Programs can complete with an error. I'm not sure what kind of shell you are using, but with a bash shell, you can type echo $? to get the return code of the last executed program.
To understand why this is, consider this: Most of the time, you do not want the entire system to come to a halt. You do, however, want to know that something went wrong. So it is common to call something, get the return value, then react appropriately, rather than let the entire thing blow up.
If you're on Windows, yes, returning anything is business as always. I'm not sure about other systems, but I've never heard of using a different return value in main to indicate something bad has happened to the user.
The actual use for return values is just as you know them, to get information back. The return value of main is used the same way. If you're in A.exe and call B.exe, then you can use main's return value to indicate whether or not B.exe ran successfully. However, where you're at now, you'll never do that, hence you just always return 0.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What should main() return in C/C++?
What does main return?
I've been wondering this for a while: what is the purpose of a return 0; statement at the end of the main() function?
I know that a return statement at the end most functions returns a value to the function which called it. However, as I understand it, the main function is the starting and ending point of the program, so I'm a little confused as to why it has a return type at all?
main()
{
//code goes here
return 0; // <-- what is the point of this return statement?
}
edit: I'm pretty new to programming (first year computer science student) and after looking at some of the answers it sounds like the return statement is used to tell the caller of the function if it has completed successfully. Other than the OS and command line, is there anything else that can call a main function? thanks for the quick answers =)
It's used to tell the environment running the program whether or not it completed successfully. This is important for command-line tools if you want to run them from scripts.
You should return zero or EXIT_SUCCESS on success, or EXIT_FAILURE on failure - the constants are defined in <cstdlib>.
If you like, you can omit the return statement from the end of main - the result will be the same as returning zero. This is a special case for main only - you must still return a value from any other non-void function.
Other than the OS and command line, is there anything else that can call a main function?
No - C++ specifically prohibits calling main from within the program.
The return usually indicates whether the process executed correctly or not. For example, you could return a -1 if there was an error.
The return value provides an exit status to the caller. When you return or exit(0) that indicates that your program ran and completed successfully. If you determine that your program has not completed successfully you can return other values. By the way the signature is int main.
It is the value returned to the OS. For example on UNIX based systems you can poll the value on your shell or in a script using $?
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the proper declaration of main?
Without citing any code in particular, I am looking for an explanation of the below example:
#include <iostream>
int main()
{
std::cout << "Hello world" << std::endl;
return 0;
}
I don't understand what return 0 does. Can you please explain this in as plain English as possible?
This defines the exit status of the process. Despite being an int, on Unix-like systems, the value is always in the range 0-255 (see Exit and Exit Status). On Microsoft systems you may use 32-bit signed integers as exit codes, which you can check with %ERRORLEVEL%. For portability, I'd recommend sticking to the 0-255 range.
Here is a trivial example:
$ cat -n exit_code.cpp
1 int main()
2 {
3 return 42;
4 }
5
Build:
$ make exit_code
g++ exit_code.cpp -o exit_code
Run (in bash):
$ ./exit_code
Check the exit status:
$ echo $?
42
Conventionally, a status of zero signifies success and non-zero failure. This can be useful in shell scripts, and so forth to indicate the level of failure, if any:
$ ./exit_code
exit_status=$?
if [[ ${exit_status} ]] ; then
echo "The process failed with status ${exit_status}."
else
echo "Success!"
fi
The process failed with status 42.
Following the comments below...
In the standard C++ header <cstdlib>, the following macros are defined:
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
However, the Exit Status section of the GNU C Library documentation, describing the same macros, sagely states:
Portability note: Some non-POSIX systems use different conventions for exit status values. For greater portability, you can use the macros EXIT_SUCCESS and EXIT_FAILURE for the conventional status value for success and failure, respectively. They are declared in the file stdlib.h.
General returning
Every function has a return type.
In the below example, the type is void, which is an "incomplete type" with no values; using this as the return type means that the function returns no value:
void foo() {
std::cout << "Hello world\n";
}
However, in the below example, the return type is int:
int foo() {
return 3;
}
The return statement determines what value calls to function foo will evaluate to. So, std::cout << foo() will result in "3" being printed to standard output.
returning from main, specifically
When the function in question happens to be the "main" function, or the program's entrypoint, it's a bit more special, because the "return value" of the "main" function is taken to be the program's "exit code" — it tells the calling environment (e.g. terminal session) whether the program's execution was deemed to be successful. It must be an int, and a value of 0 here means "everything went fine":
It's worth noting that you can actually completely omit return 0; in the "main" function as it will be included implicitly. This doesn't help you much, though, if you want to return 1; or some other value, and it doesn't come into play with other functions.
Citations
[C++11: 3.6.1/5]: A return statement in main has the effect of
leaving the main function (destroying any objects with automatic
storage duration) and calling std::exit with the return value as the
argument. If control reaches the end of main without encountering a
return statement, the effect is that of executing return 0;
[C++11: 18.5/8]:
[[noreturn]] void exit(int status)
The function exit() has additional behavior in this International Standard:
First, objects with thread storage duration and associated with the current thread are destroyed.
Next, objects with static storage duration are destroyed and functions registered by calling atexit are called. See 3.6.3 for the order of destructions and calls. (Automatic objects are not destroyed as a result of calling exit().)
If control leaves a registered function called by exit because the function does not provide a handler for a thrown exception, terminate() shall be called (15.5.1).
Next, all open C streams (as mediated by the function signatures declared in <cstdio>) with unwritten buffered data are flushed, all open C streams are closed, and all files created by calling tmpfile() are removed.
Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
Bootnote
I suggest one of these resources, as this sort of thing is explained properly in any decent peer-reviewed C++ book; YouTube tutorials are not a good way to learn C++, and Stack Overflow contributors will generally expect you to have a decent book to form your prior research before resorting to asking for help.
It's used because you may use your program as a command line tool. If there is another process waiting for the output of your program you may choose to return 0 if everything is successful, -1 if there was an error or any other constant, according to what you want to communicate.
Think of your boss telling you to go pick up the mail. After you pick up the mail, you tell your boss that everything went okay.
The operating system is the boss, the program is you. And all return 0 does is tells the operating system that everything went okay.
Under windows you can test for return value as follows (in batch script):
MyAppTest.exe
#if "%ERRORLEVEL%" == "0" goto success
echo Failure
goto end
:success
echo Success
:end
Returning from main() has the same effect as calling std::exit() and passing the return value as the status parameter.
The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:
Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
return is used to escape the function. Returning the value 0 simply allows it to exit with a code: 0. Also, returning with 0 claims a successful exit of the application.
Depends on operating system, but an exit code of 0 means success on UNIX, VMS and Windows
The return value from the main function is returned to the calling application or process (a lot of times this is a shell script). The return value is used to signal the exit status of the application.
There are no hardened rules at to what the return value should be but, by convention a return value of zero signifies normal application exit. Any non-zero value signifies abnormal application exit.
In simple applications like yours the returned value means nothing. If there is an observing process (like if one program launches another) it can be an easy way to get communicate a status or error code.
For a simple application which does not have an status or error codes, most people return 0 for a normal application exit (usually success) and return 1 if the app. fails to properly execute.
0 is an integer.
Your main function has to return an integer.
Just look at:
int main()
int stands for integer and return in this case, returns 0: an integer to terminate the program.
Usually for an error you have to return 1; 0 is the conventional value for success.
On a modern operating system, every program will exit with a specific "exit code".
DISCLAIMER NO 1.: The actual specification of that concept (of having an exit code at all) is out of the scope of any programming language specification at all. So: ANYONE asking me again about a reference to a standard may please retreat into itself, and think about a better answer for the moment.
DISPLAIMER NO 2.: The actual values of those exit codes are not specified in not actual "programming language specification", because that is out of the scope of a "programming language specification".
So long, practice has shown, that an exit code of "0" means "success", and any other code signals an error...