开发者

Test conditions in C++ [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the difference between these (bCondition == NULL) and (NULL==bCondition)?

Why do some people write instead of:

if(someVar == 0) {}

this:

if(0 == 开发者_JS百科someVar) {}

What is the difference ?

Thanks.


It's a largely deprecated practice, that was used to prevent accidental assignment '=' rather than the intended comparison '=='. Most compilers will flag this mistake as an error.

Must surely be a duplicate....


Just a good practice. If by mistake, you use single = instead of ==, finding the bug in the first one is very difficult but the second one would fail to compile clearly showing the line of error.


to avoid a mistake

if (someVar = 0) {}

instead of

if (someVar == 0) {}


When writing this:

if(someVar == 0) {}

It's easy to forget an equal-sign-character. And then you get this:

if(someVar = 0) {}

Which is perfectly valid C++, but probably not what you want.

If you forget an equal-sign-character in the other example, you get this:

if(0 = someVar) {}

which is invalid C++, and the compiler will tell you that you have done something wrong.


If instead of

(0 == someVar) 

you write

(0=someVar)

the compiler will issue an error (you try to assign to an rvalue). But if you write

(someVar=0)

the compiler will tell you nothing and you will most likely end up with a bug (the affectation return the value on its right side, here 0, so the condition will always be considered false. Moreover it changes the value of someVar). So reversing the operand allows the compiler to tells you that you've made an error. Some people call it the yoda conditionnal because it seems to be written backwards :)


No difference. Just syntactical preference. Doesn't make a lot of sense grammatically though. I've heard this called 'Yoda coding' before, because it sounds like something Yoda would say, i.e. 'Blue is the sky', instead of 'The sky is blue.'.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜