gpt4 book ai didi

c++ - if (NULL == pointer) 和 if (pointer == NULL) 有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 16:59:16 32 4
gpt4 key购买 nike

使用有什么区别:

if (NULL == pointer) 

并使用:

if (pointer == NULL)    

我的教授说使用前者而不是后者,但我看不出两者之间的区别。

最佳答案

没有区别。你的教授喜欢叫什么 Yoda conditions另见 "Yoda Conditions", "Pokémon Exception Handling" and other programming classics .

它应该防止在比较中错误地使用赋值(=)而不是相等(==),但现代编译器现在应该警告这一点,所以不需要这种类型的防御性编程。例如:

if( pointer = NULL )

NULL 分配给 pointer 而程序员的真正意思是:

if( pointer == NULL )

本来应该是比较的,哎呀。使用 Yoda 条件将此错误设为错误 ( see it live ),并显示与此类似的消息:

error: expression is not assignable

正如 jrok 指出的那样:

if (!pointer)

在这种情况下一起避免了这个问题。

这里是一个具体的例子,说明为什么使用现代编译器我们不再需要这种技术( see it live ):

#include <iostream>

int main()
{
int *ptr1 = NULL ;

if( ptr1 = NULL )
{
std::cout << "It is NULL" << std::endl ;
}

}

注意所有警告:

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,你可以看看What are the advantages of using nullptr?了解所有详情。

请注意,在 C++ 中,不太可能出现运算符重载的情况,即它们可能不相同。

请注意,-Wparentheses warning在某些方面强制进行样式选择,您要么需要在生成警告的地方放弃可能有效的赋值使用,例如,如果您使用 -Werror 或选择将这些情况括起来,其中一些正如下面的评论所暗示的,可能会觉得丑陋。我们可以使用 -Wno-parentheses 关闭 gccclang 中的警告,但我不推荐这种选择,因为警告通常会指示一个真正的错误。

关于c++ - if (NULL == pointer) 和 if (pointer == NULL) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106713/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com