if(NULL == pointer)vs if(pointer == NULL)有什么区别? [英] What is the difference between if (NULL == pointer) vs if (pointer == NULL)?
问题描述
使用之间的区别:
if (NULL == pointer)
并使用:
if (pointer == NULL)
我的教授说使用前者而不是后者,两者之间的差异。
My professor says to use the former over the latter but I don't see the difference between the two.
推荐答案
没有区别,它被称为 Yoda条件还可以查看Yoda条件,Pokémon异常处理和其他编程经典。
There is no difference, it is called Yoda conditions also see "Yoda Conditions", "Pokémon Exception Handling" and other programming classics.
应该防止使用赋值 =
)在比较中错误地等于( ==
),但现代编译器现在应该警告这种类型的防御性规划不应该需要。例如:
It is supposed to prevent the usage of assignment(=
) by mistake over equality(==
) in a comparison, but modern compilers should warn about this now, so this type of defensive programming should not be needed. For example:
if( pointer = NULL )
会将 NULL
分配给指针
:
if( pointer == NULL )
它应该是一个比较,糟糕。使用 Yoda条件将此错误( ),并附上类似的讯息:
it should have been a comparison, Oops. Make this an error using Yoda conditions you will (see it live), with a similar message to this:
错误:表达式无法指派
error: expression is not assignable
正如jrok指出的:
if (!pointer)
在这种情况下避免这个问题。
avoids this problem all together in this case.
这里是一个具体的例子,为什么现代编译器我们不再需要这种技术了( see it live
Here is a concrete example of why with a modern compilers we don't need this technique anymore(see it live):
#include <iostream>
int main()
{
int *ptr1 = NULL ;
if( ptr1 = NULL )
{
std::cout << "It is NULL" << std::endl ;
}
}
请注意所有警告: p>
Note all the warnings:
warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if( ptr1 = NULL )
~~~~~^~~~~~
note: place parentheses around the assignment to silence this warning
if( ptr1 = NULL )
^
( )
use '==' to turn this assignment into an equality comparison
if( ptr1 = NULL )
^
==
这使得很难错过这个问题。值得注意的是,在 C ++ 中, nullptr 应该优先于 NULL
,您可以查看使用nullptr的好处是什么?所有的细节。
which makes it pretty hard to miss the problem. It is worth noting that in C++ nullptr should be preferred over NULL
, you can look at What are the advantages of using nullptr? for all the details.
请注意,在 C ++
请注意, - Wparentheses警告在某些方面强制样式选择,您需要放弃潜在的有效使用分配产生警告的位置,例如,如果您使用 -Werror
或选择括号括起这些情况,有些人可能会发现丑陋建议。我们可以使用 -Wno-parentheses $来打开
gcc
和 clang
c $ c>但我不会推荐这个选择,因为警告一般会指示一个真正的错误。
Note, the -Wparentheses warning in some ways forces a style choice, you either need to give up potentially valid uses of assignment in places where the warning is generated, for example if you use -Werror
or choose to parenthesize those cases, which some may find ugly as the comment below suggests. We can turn of the warning in gcc
and clang
using -Wno-parentheses
but I would not recommend that choice since the warning in general will indicate a real bug.
这篇关于if(NULL == pointer)vs if(pointer == NULL)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!