3

I know that multiple expressions are evaluated from right to left. Ex:

int i = 0;   
printf("%d %d %d", i, i++, i++); // Prints 2 1 0

But when it comes to each expression to be evaluated, i'm not getting if it is from right to left or vice versa.

int main()
{
    int a = 1, b = 1, d = 1;
    printf("%d", a + ++a); // Result = 4
}

Considering evaluation from left to right, the preceding code should be evaluated as 1 + 2 = 3

int main()
{
    int a = 1, b = 1, d = 1;
    printf("%d", ++a + a); // Result = 4
}

And this should Evaluate as 2 + 2 = 4

But in both the cases the answer is 4.

Can anyone explain how these expressions are evaluated?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Nir_J
  • 133
  • 1
  • 3
  • 7
  • 1
    _I know that multiple expressions are evaluated from right to left. Ex:_ `int i = 0; printf("%d %d %d", i, i++, i++); // Prints 2 1 0`: **Wrong**, is undefined behavior. – David Ranieri Aug 26 '16 at 08:16
  • @AlterMann This question contain 2 issues: order of evaluation of function arguments, and poorly sequenced operations of the same variable in the same expression. That duplicate only explains the latter, I'll re-open this. – Lundin Aug 26 '16 at 08:22
  • 1
    @Lundin Thus you reopened it incorrectly. The duplicate does in fact explain order: http://stackoverflow.com/a/18260171/4082723, http://stackoverflow.com/a/949508/4082723 – 2501 Aug 26 '16 at 08:29
  • @2501 Fair enough, but the actual question in that duplicate contains no order of evaluation issues, so it might be rather confusing for the OP. – Lundin Aug 26 '16 at 08:32
  • And someone, this time silently, reopened it again. Great! – 2501 Aug 26 '16 at 08:38
  • @2501 It isn't a great duplicate. Ideally a duplicate would address both issues in the question. Until someone finds such a beast, my answer links to that post anyway. – Lundin Aug 26 '16 at 08:48

1 Answers1

5

I know that multiple expressions are evaluated from right to left.

No. The order of evaluation of function parameters is unspecified behavior. Meaning you can't know the order, it may differ from system to system or even from function call to function call. You should never write programs that rely on this order of evaluation.

In addition, there is no sequence point between the evaluation of function parameters, so code like printf("%d", ++a + a); also invokes undefined behavior, see Why are these constructs (using ++) undefined behavior?.

Please note that operator precedence and operator associativity only guarantees the order in which an expression is parsed! This is not related to the order of evaluation of the operands. (With a few special exceptions such as || && , ?: operators.)

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396