Govan Gova
Govan Gova

Reputation: 53

The order of cout messages is not as expected

I am confused with the output of below code when I execute it.

Code:

int add(int a, int b)
{
    cout<<"inside int add function"<<endl;
    return a+b;
}

float add(float a, float b)
{
    cout<<"inside float add function"<<endl;
    return a+b;
}

int main()
{
    cout<<add(10.0f,20.0f)<<endl<<add(20,50); 
    return 0;
}

output:

inside int add function
inside float add function
30
70

I dont understand the order of cout messages are getting printed in console. But I expected the output of above program like below

inside float add function
30
inside int add function
70

Could someone explain about above behavior.

Upvotes: 5

Views: 268

Answers (2)

melchor629
melchor629

Reputation: 342

the line cout<<add(10.0f,20.0f)<<endl<<add(20,50); is expected to print your output:

inside int add function
inside float add function
30
70

Thats because to print to cout firstly calls add(10.0f , 20.0f) and stores the output to a internal variable, then calls add(10, 20) and stores the output to another internal variable, and finally it prints the returned values. Something like this:

float a = add(10.0f, 20.0f);
int b = add(10, 20);
cout << a << endl << b;

In this case, if you want to print as you wish, try to print first one function, and then the other:

cout << add(10.0f, 20.0f) << endl;
cout << add(10, 20);

Upvotes: 1

Massimiliano
Massimiliano

Reputation: 8042

This line in you code:

cout<<add(10.0f,20.0f)<<endl<<add(20,50);

will be translated by the compiler into:

operator<<(operator<<(operator<<(cout,add(10.0f,20.0f)),endl),add(20,50));

As the order of evaluation of function parameters is not mandated by the standard, it just happens that add(20,50) is evaluated before operator<<(operator<<(cout,add(10.0f,20.0f)),endl).

Upvotes: 7

Related Questions