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.
std::cout is used to output a value (cout = character output) std::cin is used to get an input value (cin = character input) << is used with std::cout, and shows the direction that data is moving (if std::cout represents the console, the output data is moving from the variable to the console).
cout is a predefined object of the ostream class. “std::cout” calls the Standard Template/Iostream Library, since “cout” is only defined in the “std” namespace. 3.
The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.
Both + and << are left-associative, which means they're evaluated from left to right. In the case of overloaded operators, the operator is replaced with the equivalent function call. std::cout << value1 << " and done!" << std::endl; First, << is left associative, so you start on the left.
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)
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With