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 。
可是我这边运行后现实是先判断后减。
为啥啊?
|
jimzhongFeb 17, 2017
1
val--是先返回 val 的值,然后再减 1
|
|
liuhaotianFeb 17, 2017
4
运算符优先级 和 运算符返回值是不一样的。
--val 的返回值是 val-1 val-- 的返回值是 val 如果不能理解为什么运算符有返回值的话,可以搜一下“运算符重载” |
|
ZirconiFeb 17, 2017
5
这涉及到所谓的 sequence point 的概念。
还有这不是 C++代码吗。。。 |
|
liuhaotianFeb 17, 2017
6
@Zirconi
那我觉得 undefined behavior 更是玄学 hhh |
|
7
ok ,我明白了。脑子朽住了。
|
|
bluefalconjunFeb 17, 2017
8
@liuhaotian c 玄学很有意思... 哈哈
|
|
CbdyFeb 17, 2017
10
这种写法俗称耍小聪明
|
|
visionsmileFeb 17, 2017
12
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 ]
|
|
visionsmileFeb 17, 2017
13
The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool.
|
|
ningcoolFeb 17, 2017
14
你可以试试 --val 返回 0
|
|
fei051466Feb 17, 2017
15
刚学编程的时候这个老考, hhhh
|
|
ryd994Feb 18, 2017 via Android
16
说实话,编程课考这种屁用没有
能不能好好写代码,明明一个 for 能解决的问题 这样编译器很难办的好不好,都没法优化 |
|
snnnFeb 18, 2017
18
你是分不清 i++ 和 ++i 吧?
|