【发布时间】:2018-08-04 10:06:01
【问题描述】:
我问自己是否可以通过以下 if 条件在 C++ AND C 中进行短路:
uvc_frame_t *frame = ...; //receive a new frame
if(frame != NULL && frame->data != NULL) cout << "Data read";
else cout << "Either frame was NULL or no data was read!";
我不确定此语句是否会引发分段错误,因为如果 frame 是 NULL,那么您将无法检查 frame->data!
-
while循环条件也一样吗?while(frame == NULL && frame->data == NULL) { //.. receive frame } ||运算符也一样吗?- 如何强制评估 if 语句中的所有值(即使我检查 3 个变量)
这是frame 的底层结构:
typedef struct uvc_frame {
void *data;
size_t data_bytes;
uint32_t width;
uint32_t height;
enum uvc_frame_format frame_format;
size_t step;
uint32_t sequence;
struct timeval capture_time;
uvc_device_handle_t *source;
uint8_t library_owns_data;
} uvc_frame_t;
【问题讨论】:
-
检查指针是否不为空,然后 && 以在同一个表达式中访问其方法非常好,但您的 while 循环则相反
-
据我所知,短路评估在 C 和 C++ 中的行为相同。
-
您能澄清一下“强制评估所有值”是什么意思吗?
-
在现代 C++ 中,最好将指针与
nullptr进行比较,而不是NULL。 stackoverflow.com/questions/1282295/what-exactly-is-nullptr
标签: c++ if-statement segmentation-fault short-circuiting