ankur suman
ankur suman

Reputation: 151

order of function call inside cout

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"

Upvotes: 4

Views: 262

Answers (1)

Drax
Drax

Reputation: 13278

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

Upvotes: 5

Related Questions