检查是否为复合,然后C中的其他条件总是安全的? [英] Is compound if checking for null and then other condition in C always safe?

查看:112
本文介绍了检查是否为复合,然后C中的其他条件总是安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这个问题是复合如果检查为null,然后C ++中的其他条件总是安全吗?但是关于C ,而不是C ++。有人指出问题应该更多具体)。

(this question is an exact copy of Is compound if checking for null and then other condition in C++ always safe? but about C, not C++. It was pointed out that the question should be more specific).

我一直在使用以下类型的 if 条件很长时间。

I have been using the following type of if condition for a lot of time.

char* ptr = ...;
if (ptr != NULL && ptr[0] != '\0') // <=== is this always safe?
{ /* ... */ }

它依赖于 ptr!= NULL ptr [0]之前检查!='\ 0'

在所有标准,编译器和架构下是否安全?或者是否有可能在 ptr!= NULL ptr [0]!='\ 0' >?

Is it safe under all standards, compilers, architectures? Or is there a possibility that ptr[0] != '\0' will be checked before ptr != NULL?

推荐答案

是的,这是安全的。

C标准说(N1570 - 6.5.13逻辑AND运算符):

C standard says (N1570 - 6.5.13 Logical AND operator):


与按位二进制和&操作员,&&运营商保证从左到右的评估;
如果计算第二个操作数,则在第一个和第二个操作数的
的计算之间存在一个序列点。如果第一个操作数比较等于0,则不计算第二个
操作数。

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

这篇关于检查是否为复合,然后C中的其他条件总是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆