Several unary operators in C and C++

前端 未结 3 1242
孤独总比滥情好
孤独总比滥情好 2021-01-26 05:18

Is it standard-conforming to use expressions like

int i = 1;
+-+-+i;

and how the sign of i variable is determined?

相关标签:
3条回答
  • 2021-01-26 05:30

    Yes it is. Unary + and - associate right-to-left, so the expression is parsed as

    +(-(+(-(+i))));
    

    Which results in 1.

    Note that these can be overloaded, so for a user-defined type the answer may differ.

    0 讨论(0)
  • 2021-01-26 05:51

    Your operators has no side effect, +i do nothing with int itself and you do not use the temporary generated value but remove + that do nothing and you have -(-i) witch is equal to i itself.(removing + in the code will convert the operator, I mean remove it in computation because it has no effect)

    0 讨论(0)
  • 2021-01-26 05:53

    i isn't modified (C: without intervening sequence points|C++: in an unsequenced manner) so it's legal. You're just creating a new temporary with each operator.

    The unary + doesn't even do anything, so all you have is two negations which just give 1 for that expression. The variable i itself is never changed.

    0 讨论(0)
提交回复
热议问题