int main(int argc,char* argv[]) { int val = 1; if (val-- == 0) cout << "hello,world" << endl; }
能打印出来 hello,world 吗?
我之前的理解是--运算优先级要高于==,所以这个应该是先做减操作,然后再判断,最后打印 hello,world 。
可是我这边运行后现实是先判断后减。
为啥啊?

int main(int argc,char* argv[]) { int val = 1; if (val-- == 0) cout << "hello,world" << endl; }
能打印出来 hello,world 吗?
我之前的理解是--运算优先级要高于==,所以这个应该是先做减操作,然后再判断,最后打印 hello,world 。
可是我这边运行后现实是先判断后减。
为啥啊?
1 jimzhong Feb 17, 2017 val--是先返回 val 的值,然后再减 1 |
4 liuhaotian Feb 17, 2017 运算符优先级 和 运算符返回值是不一样的。 --val 的返回值是 val-1 val-- 的返回值是 val 如果不能理解为什么运算符有返回值的话,可以搜一下“运算符重载” |
5 Zirconi Feb 17, 2017 这涉及到所谓的 sequence point 的概念。 还有这不是 C++代码吗。。。 |
6 liuhaotian Feb 17, 2017 @Zirconi 那我觉得 undefined behavior 更是玄学 hhh |
7 hailongs OP ok ,我明白了。脑子朽住了。 |
8 bluefalconjun Feb 17, 2017 @liuhaotian c 玄学很有意思... 哈哈 |
10 Cbdy Feb 17, 2017 这种写法俗称耍小聪明 |
12 visionsmile Feb 17, 2017 The value of a postfix ++ expression is the value of its operand. [ Note: the value obtained is a copy of the original value end note ] |
13 visionsmile Feb 17, 2017 The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool. |
14 ningcool Feb 17, 2017 你可以试试 --val 返回 0 |
15 fei051466 Feb 17, 2017 刚学编程的时候这个老考, hhhh |
16 ryd994 Feb 18, 2017 via Android 说实话,编程课考这种屁用没有 能不能好好写代码,明明一个 for 能解决的问题 这样编译器很难办的好不好,都没法优化 |
18 snnn Feb 18, 2017 你是分不清 i++ 和 ++i 吧? |