order of expression evaluation

Feb 8, 2009 at 7:42pm
hey can somebody please explain to me what is the order of evaluation of expressions in cout/printf and the order of printing i.e. whether it is left-to-right or vice-versa?

what will be the output?
printf("%d %d\n",i+++j,++i,j++);

what will be the value of i if i=+ - + - + - +4?
can continue be used in switch statement just like it is used in loop constructs?
Feb 8, 2009 at 7:52pm
1. i+++j
You can't do that. It's ambiguous. Is it "i++ + j" or "i + ++j"?
The order of execution of prefix and postfix increments and decrements is undefined.
In some compilers
b=a++ + a;
is the same as
1
2
b=a+a;
a++;

While in others, it's the same as
1
2
3
b=a;
a++;
b+=a;


2. +-+-+-+4==---4==-4. That's in mathematics, anyway. I'm not entirely sure + can be used as a unary operator.

3. No, it can't.
Feb 8, 2009 at 8:22pm
I'm pretty sure that even the order of expressions used as parameters to a function is undefined. The compiler may choose to evaluate in any order that it wants for optimization.

For a single expression, though, there is an order of operations that is defined in the C++ standard. As mentioned above, there are some statements that remain undefined by the standard and should be avoided.
Feb 8, 2009 at 9:19pm
On second thought, I think each of the arguments are evaluated as separate expressions, so that function call would have a defined and consistent result.

As for order of parameter-passing, a teacher once told me parameters are passed (and arguments evaluated) from right to left in order to support variadic arguments, however:
The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.
-The C++ Standard, Section 5.2.2, paragraph 8.
Last edited on Feb 8, 2009 at 9:19pm
Topic archived. No new replies allowed.