What will be printed as the result of the operation below:
x=5;
printf("%d,%d,%d\n",x,x<<2,x>>2);
Answer: 5,20,1
I thought order is undefined yet I found above as interview question on many sites.
What will be printed as the result of the operation below:
x=5;
printf("%d,%d,%d\n",x,x<<2,x>>2);
Answer: 5,20,1
I thought order is undefined yet I found above as interview question on many sites.
Bit shift operators don't modify the value of the variable... so order doesn't matter.
The order of evaluation is unspecified, but it doesn't matter because you're not modifying x
at all.
So the program is well-defined, and the answer is as given.
The following would have undefined semantics:
printf("%d,%d,%d\n", x, x <<= 2, x >>= 2);
From the C++ standard:
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.
However, your example would only have undefined behavior if the arguments were x>>=2
and x<<=2
, such that x were being modified.
I found the answer in c++ standards.
Paragraph 5.2.2.8:
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.
In other words, It depends on compiler only.
The order of evaluation is undefined in the Official C Specification.
However, as a matter of practicality, parameters are usually evaluated right-to-left.
In your problem, the bit-shift operator doesn't change the value of X, so the order of evaluation is not important. You'd get 5,20,1, whether evaluated left-to-right, right-to-left, or middle-first.
In C, parameters are pushed on to the stack in a right-to-left order, so that the 1st param (in this case, the char* "%d,%d,%d") is at the top of the stack. Parameters are usually (but not always) evaluated in the same order they are pushed.
A problem that better illustrates what you're talking about is:
int i=1;
printf("%d, %d, %d", i++, i++, i++);
The official answer is "undefined".
The practical answer, (in the several compilers/platforms I've tried), is "3, 2, 1".