开发者

~0 vs. !0 vs. 1 in C

I was reading some code today by someone I consider to be a reasonable programmer, and I noticed they used a =~0 to set a loo开发者_StackOverflow中文版p quit variable.

Is there any compelling reason to do this rather than simply quit = 1;?

I'm mostly just curious, before I go ahead and change it. Thanks!

Example:

while(!quit){
    ...;

    if(!strcmp(s, "q")) 
        quit=~0;
}


There is no strong reason for that, unless some other code tests quit differently, such as testing any other bit. !0 is one, but ~0 is -1 on all modern architectures.

On some architectures ~0 is faster than !0, though that should be optimized away by any decent compiler.


~0 is usually -1, while !0 is defined to be 1.

Of course, !~0 and !!0 are both 0, so there is no compelling reason to use one or the other, aside from the fact that ~0 is non-idiomatic (meaning that people won't know what the heck you're doing).


In C, ~ is the unary operator for ones compliment which flips bits to their opposite state. So technically the code works because the if() clause is only evaluating for the presence of 0 (false) or anything not 0 (true). Frankly I think this is a bit overkill for evaluating true or false. I'd only consider using it if I was truly doing evaluations on a bitwise basis. Maybe there could be an argument made for performance but I somehow doubt it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜