开发者

How is this Precedence operators working?

I know this is silly question but I don't know which step I'm missing to count so can't understand why the output is that of this code.

int i=2;

int c;

c = 2 * - ++ i << 1;

cout<< c;

I have trouble to understanding this line in this code:

c = 2 * - ++ i <<1;

I'm gettin开发者_JAVA技巧g result -12. But I'm unable to get it how is precedence of operator is working here?


Have a look at the C++ Operator Precedence table.

  1. The ++i is being evaluated, yielding 3.
  2. The unary - is being evaluated, yielding -3.
  3. The multiplication is being done1, yielding -6.
  4. The bit shift is evaluated (shifting left by 1 is effectively multiplying by two) yielding -12.
  5. The result -12 is being assigned to the variable c.

If you used parentheses to see what operator precedence was doing, you'd get

c = ((2 * (-(++i))) << 1);

Plus that expression is a bit misleading due to the weird spacing between operators. It would be better to write it c = 2 * -++i << 1;

1 Note that this is not the unary *, which dereferences a pointer. This is the multiplication operator, which is a binary operator.


Operator precedence defined the grouping between the operators and their operands. In your example the grouping is as follows

c = ((2 * (-(++i))) << 1);

That's how "precedence of operator is working here" and that's the only thing it does.

The result of this expression is -6 shifted one bit to the left. This happens to be -12 on your platform.

According to your comment in another answer, you mistakenly believe that operator precedence somehow controls what is executed "first" and what is executed "next". This is totally incorrect. Operator precedence has absolutely nothing to do with the order of execution. The only thing operator precedence does, once again, is define the grouping between the operators and their operands. No more, no less.

The order of execution is a totally different thing entirely independent from operator precedence. In fact, C++ language does not define any "order of execution" for expressions containing no sequence points inside (the above one included).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜