Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of function call inside cout

Tags:

c++

cout

c++14

I am trying to know the order of execution of functions inside the cout statement

I tried this set of codes

#include < iostream >
using namespace std;
int i=0;
int sum(int a)
{
    i++;
    return a+i;
}
int main()
{
    cout << sum(3) << sum(2) ;
    return 0;
}

"I expected the output to be 44, but the actual output is 53"

like image 911
ankur suman Avatar asked Oct 21 '25 03:10

ankur suman


1 Answers

As stated here: https://en.cppreference.com/w/cpp/language/eval_order

Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+, but the function call to c may be evaluated first, last, or between a() or b() at run time

In your line

cout << sum(3) << sum(2)

the order of the two operator<< calls depends on the operator you use (here << so left-to-right), but the evaluation of each subexpression, namely sum(3) and sum(2) has no defined order and depends on the mood (most optimized compile approach usually) of your compiler.

For info here is a list of operators associativity: https://en.cppreference.com/w/cpp/language/operator_precedence

like image 95
Drax Avatar answered Oct 23 '25 18:10

Drax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!