If 语句中的多指针测试
考虑指向结构的指针
struct a_struct
{
int A;
};
可以这样做:
struct a_struct *ptr;
//...
if( ptr != NULL && ptr->A == 1)
{
//work with ptr struct
}
还是应该在测试其字段之前测试指针是否有效。
if(ptr != NULL)
{
if(ptr->A == 1)
{
//work with ptr struct
}
}
considering a pointer to a struct
struct a_struct
{
int A;
};
Is it ok to do :
struct a_struct *ptr;
//...
if( ptr != NULL && ptr->A == 1)
{
//work with ptr struct
}
or should you Test if the pointer is valid before testing for on of its field.
if(ptr != NULL)
{
if(ptr->A == 1)
{
//work with ptr struct
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,没关系。
C 中的
&&
运算符短路,因此仅当ptr
为非时才会计算ptr->A == 1
-无效的。Yes, that's ok.
The
&&
operator short-circuits in C, soptr->A == 1
will only be evaluated ifptr
is non-null.仅当第一个测试成功时,
&&
才会评估第二个测试,因此您的代码(一个if
语句)完全没问题。&&
evaluates the second test only if the first was successful, so your code (oneif
statement) is perfectly fine.这会起作用,而且实际上是一个相当常见的习惯用法。如果您编写 else 子句,则必须担心哪个检查将您踢到那里,但这与任何其他多条件 if 检查没有什么不同。
That will work, and is actually a fairly common idiom. If you write an
else
clause, you do have to worry about which check kicked you there, but that is no different from any other mult-conditionif
-check.