c 语言运算符问题

2017-02-17 13:21:54 +08:00
 hailongs

int main(int argc,char* argv[]) { int val = 1; if (val-- == 0) cout << "hello,world" << endl; }

能打印出来 hello,world 吗?

我之前的理解是--运算优先级要高于==,所以这个应该是先做减操作,然后再判断,最后打印 hello,world 。

可是我这边运行后现实是先判断后减。

为啥啊?

http://www.jb51.net/article/37282.htm

2177 次点击
所在节点    C
18 条回复
jimzhong
2017-02-17 13:23:44 +08:00
val--是先返回 val 的值,然后再减 1
hailongs
2017-02-17 13:25:30 +08:00
@jimzhong n 那什么时候会出现--和==的比较呢?
hailongs
2017-02-17 13:28:42 +08:00
@jimzhong 擦,明白了。。。被坑了,程序里这样搞了下。差点死掉。
liuhaotian
2017-02-17 13:28:49 +08:00
运算符优先级 和 运算符返回值是不一样的。

--val 的返回值是 val-1
val-- 的返回值是 val

如果不能理解为什么运算符有返回值的话,可以搜一下“运算符重载”
Zirconi
2017-02-17 13:29:07 +08:00
这涉及到所谓的 sequence point 的概念。
还有这不是 C++代码吗。。。
liuhaotian
2017-02-17 13:30:24 +08:00
@Zirconi
那我觉得 undefined behavior 更是玄学 hhh
hailongs
2017-02-17 13:30:29 +08:00
ok ,我明白了。脑子朽住了。
bluefalconjun
2017-02-17 14:32:31 +08:00
@liuhaotian c 玄学很有意思... 哈哈
chengluyu
2017-02-17 14:34:27 +08:00
@Zirconi 在楼主的例子里不涉及 seq point 。
Cbdy
2017-02-17 14:58:35 +08:00
这种写法俗称耍小聪明
Zirconi
2017-02-17 15:32:04 +08:00
@chengluyu 是的,看错了。。
visionsmile
2017-02-17 18:14:14 +08:00
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 ]
visionsmile
2017-02-17 18:16:47 +08:00
The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool.
ningcool
2017-02-17 18:36:59 +08:00
你可以试试 --val 返回 0
fei051466
2017-02-17 20:42:36 +08:00
刚学编程的时候这个老考, hhhh
ryd994
2017-02-18 02:12:51 +08:00
说实话,编程课考这种屁用没有
能不能好好写代码,明明一个 for 能解决的问题
这样编译器很难办的好不好,都没法优化
pagict
2017-02-18 13:20:22 +08:00
@ryd994 编译器的优化应该是基于汇编的吧
snnn
2017-02-18 22:12:08 +08:00
你是分不清 i++ 和 ++i 吧?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/341167

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX