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?
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.)