What double negation does in C

后端 未结 5 669
谎友^
谎友^ 2021-01-14 05:34

I had a controversy about what compilers \"think\" about this:

a = 8;
b = !!a;

So, is b == 0x01 ? Is TRUE always

5条回答
  •  没有蜡笔的小新
    2021-01-14 05:55

    !!a will be either 0 or 1, and will be type int. It will be 0 for zero a, and 1 otherwise.

    As for your choices (a) and (b), they are not equivalent, due to a possibility of a being negative. That aside, you could argue that a > 0 ? 1 : 0 is clearer but in performance-critical applications !!a may be better as it will not branch whereas a ternary conditional could dump the pipeline. But a good compiler will optimise out either way. I seldom use either since things like if (a) and if (!!a) are functionally equivalent.

提交回复
热议问题