Hallo everyone,

I've been studying C++ active for a couple of days. And I was thinking about that all my codes and with:

{
    return 0;
}

So I wanted to know why and in my book I found:

The only statement in this block is a return, which is a statement that terminates a function. As is the case here, a return can also send a value back to the function’s caller. When a return statement includes a value, the value returned must have a type that is compatible with the return type of the function. In this case, the return type of main is int and the return value is 0, which is an int.

But I don't really understand this, for me it's a difficult explained. Like what is a function in C++ programming, a function's caller...?
Can someone explain it in an easier way?

Thank you for your help and time

Kareem

Recommended Answers

All 10 Replies

A function is C++ is a block of code; you sometimes feed it some parameters, and you sometimes get something back. For example, here's a simple function that adds two numbers and gives back (returns) a number:

int addTwoNumbers (int a, int b)
{
  int sum = a+b;
  return sum;
}

Here is how to use, or call this function:

int firstNumber = 5;
int secondNumber = 7;
int sum = addTwoNumbers(firstNumber, secondNumber);

If the above is news to you, throw away whatever you're using to learn C++ and get something better. To have been studying C++ for a few days and not have seen the word "function" is not good.

As far as you are concerned, your code begins at the function main. However, when you run your program, that's not actually true.

When you compile your C++ program, the program does not actually begin at the start of your main function. There is a lot that needs to be done before that, such as preparing memory. This is handled by code written by someone else and provided for you. At some point, when everything is ready, your function main is called by another function. In Linux, for example, the function _start is where your program actually starts running, and this will call __libc_start_main, and *that* function will eventually call main. __libc_start_main is expecting your main function to return a value. This is why you havereturn 0; at the end of your main function. Because the function that calls your main function is expecting something to be returned.

What is does with that value is usually kick it back upstairs and ultimately present it to whatever called the program, so it becomes the value given back to the operating system by your program.

commented: couldn't agree more about the book +10
commented: Thank you for your reply. It helped me alot. I also found function and return in the book but not very detailed, it's covered in later chapters. +0

And for whatever reason, 0 is traditionally the value a program returns upon normal completion. You can return other values and for the purposes of your program define what they mean, perhaps indicating various error conditions that caused the program to not complete normally.

Just to make the point more clear for the OP,

Consider my program having following steps:
1. Add a+b;
2. A-b;
3. Hit Jack in the Head
4. Try to make noodles.
5. Again a+b.
6. Return 0;

Now if my code works fine and complete successfully, the step 6 also would have run, and i would get 0 as the result. Then i know that, the every step of the program worked fine, and reached step 6.

Otherwise, if my code stopped in between, for some reason (eg, infinite loops, errors etc), it might not have reached step 6, and returned value might not be 0. Hence i will get to know that, something didn't work as expected....

In some IDEs (VC++ for example) you can see the returned value of a program execution after its been run. something like (0*0)....

Programs can run other programs, for example I could write a program that runs PrimePackster's program. So if his program was supposed to hit jack in the head, but missed and returned an error number from main() instead of 0 then my program would know that and take some action. In that instance the operating system passes the return value of main() from PrimePackster's program to my program. The return value from main() can also be used in batch files (MS-Windows) or shello programs (*nix).

commented: OMG! Thats a wonderful addition. Thanks For that..... +3

Thank you all for your comments.
But the most thanks to Moschops,

Your explanations were very clear and better than the book, because I found them but they were less detailed and more difficult explained. Also thank you for explaining the term "function" in a easier way. When I hear function I think about maths, with f(x)= 2x + 4.
There is still one thing I don't understand. What is a function's caller?

Kareem

When I hear function I think about maths, with f(x)= 2x + 4.

Computer science and programming are rooted in mathematics, so that's not a bad way to approach the concepts. Taking your example, it translates easily to C++ like so:

int f(int x)
{
    return 2 * x + 4;
}

And by providing x, the caller can execute the function:

int main()
{
    std::cout << f(5) << '\n'; // 2 * 5 + 4
}

What is a function's caller?

The code that executes a function, provides arguments, and accepts the return value is the caller. In the example above, main() is the caller for f(), and f() is the callee.

commented: Worth it! +3

Adding to what's already said, here's a description from the specification (section 6.6.3):

A function returns to its caller by the return statement.

A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object (12.2). Flowing off the end of a function is equivalent to areturnwith no value; this results in undefined behavior in a value-returning function.

A return statement with an expression of type “cvvoid” can be used only in functions with a return type of cvvoid; the expression is evaluated just before the function returns to its caller.

<cstdlib> also contains macro's you can use for returning from the program itself. Quote from the specification again (section 18.3):

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 terminationis returned. Otherwise the status returned is implementation-defined.

Note that this description is aimed at the function "exit" which takes "status" as a parameter. However, section 3.6.1 from the specification states:

A return statement in main has the effect of leaving the main function (destroying any objects with auto-matic storage duration) and calling 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;

The previous quote related to "exit" started with "Finally". Here is the part that came before it. I don't think this is very relevent for you but adding it anyway to be a bit more complete.

First, objects with static storage duration are destroyed and functions registered by calling atexit are called. Non-local objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)(*) Functions registered with atexit are called in the reverse order of their registration, except that a function is called after any previously registered functions that had already been called at the time it was registered. (**) A function registered with atexit before a non-local object obj1 of static storage duration is initialized will not be called until obj1’s destruction has completed. A function registered with atexit after a non-local object obj2 of static storage duration is initialized will be called before obj2’s destruction starts. A local static object obj3 is destroyed at the same time it would be if a function calling the obj3 destructor were registered with atexit at the completion of the obj3 constructor.

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. (***)

(*) Objects with automatic storage duration are all destroyed in a program whose function main() contains no automatic objects and executes the call toexit(). Control can be transferred directly to such a main() by throwing an exception that is caught in main()
(**) A function is called for every time it is registered.
(***) Any C streams associated with cin, cout, etc (27.3) are flushed and closed when static objects are destroyed in the previous phase. The function tmpfile() is declared in <cstdio>.

Deceptikon

Thanks for your reply.

int f(int x)
{
    return 2 * x + 4;
}

So the 2* x + 4 is the value that is returned to the function (fx), right?

Also a last question before talking less about the post subject. The int does it stand for integer as in the numbers 1,-1,2,-2,2,-3,...?
If I'm right does the int say that the function has integer values or am I understanding int wrong?

So the 2* x + 4 is the value that is returned to the function (fx), right?

Yes.

The int does it stand for integer as in the numbers 1,-1,2,-2,2,-3,...?

Yes.

Not sure if they were just grammer error, so here you go with more clarification.......

So the 2* x + 4 is the value that is returned to the function (fx), right?

Returned 'FROM' the funtion f to the function caller.......

If I'm right does the int say that the function has integer values or am I understanding int wrong?

Not 'has' integer value, but returns an integer value.......
eg.

int integer()
{
    float a,b; //See this 'int funtion' can have floats(a and b) or any other types
    int c;
    a=3.14;
    c=10;
    b=a;
    return c; //But returned value should be an interger as this is a int function......
}

Now here is the function caller for above fn......

void main()
{
    int pan;
    pan=integer(); //The function caller....
    cout<<pan;
}

OP! What do you think will be the output of this program?? (To make sure, you got the concept).....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.