hailongs
V2EX  ›  C

c 语言运算符问题

  •  
  •   hailongs · Feb 17, 2017 · 3353 views
    This topic created in 3551 days ago, the information mentioned may be changed or developed.

    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

    18 replies  •  2017-02-18 22:12:08 +08:00
    jimzhong
    jimzhong
    Feb 17, 2017
    1
    val--是先返回 val 的值,然后再减 1
    hailongs
    hailongs
    OP
    Feb 17, 2017
    2
    @jimzhong n 那什么时候会出现--和==的比较呢?
    hailongs
    hailongs
    OP
    Feb 17, 2017
    3
    @jimzhong 擦,明白了。。。被坑了,程序里这样搞了下。差点死掉。
    liuhaotian
    liuhaotian
    Feb 17, 2017
    4
    运算符优先级 和 运算符返回值是不一样的。

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

    如果不能理解为什么运算符有返回值的话,可以搜一下“运算符重载”
    Zirconi
    Zirconi
    Feb 17, 2017
    5
    这涉及到所谓的 sequence point 的概念。
    还有这不是 C++代码吗。。。
    liuhaotian
    liuhaotian
    Feb 17, 2017
    6
    @Zirconi
    那我觉得 undefined behavior 更是玄学 hhh
    hailongs
    hailongs
    OP
    Feb 17, 2017
    7
    ok ,我明白了。脑子朽住了。
    bluefalconjun
    bluefalconjun
    Feb 17, 2017
    8
    @liuhaotian c 玄学很有意思... 哈哈
    chengluyu
    chengluyu
    Feb 17, 2017❤️1
    9
    @Zirconi 在楼主的例子里不涉及 seq point 。
    Cbdy
    Cbdy
    Feb 17, 2017
    10
    这种写法俗称耍小聪明
    Zirconi
    Zirconi
    Feb 17, 2017
    11
    @chengluyu 是的,看错了。。
    visionsmile
    visionsmile
    Feb 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 ]
    visionsmile
    visionsmile
    Feb 17, 2017
    13
    The operand of postfix -- is decremented analogously to the postfix ++ operator, except that the operand shall not be of type bool.
    ningcool
    ningcool
    Feb 17, 2017
    14
    你可以试试 --val 返回 0
    fei051466
    fei051466
    Feb 17, 2017
    15
    刚学编程的时候这个老考, hhhh
    ryd994
    ryd994
    Feb 18, 2017 via Android
    16
    说实话,编程课考这种屁用没有
    能不能好好写代码,明明一个 for 能解决的问题
    这样编译器很难办的好不好,都没法优化
    pagict
    pagict
    Feb 18, 2017 via Android
    17
    @ryd994 编译器的优化应该是基于汇编的吧
    snnn
    snnn
    Feb 18, 2017
    18
    你是分不清 i++ 和 ++i 吧?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1478 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 09:52 · PVG 17:52 · LAX 01:52 · JFK 04:52
    ♥ Do have faith in what you're doing.