I asked myself if short-circuiting in C++ AND C is possible with the following if-condition:
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!";
I'm not sure wheter this statement could throw an segmentation fault, because if frame
is NULL
then you can't check for frame->data
!
And is it the same for while
loop conditions?
while(frame == NULL && frame->data == NULL)
{
//.. receive frame
}
And is it the same for the ||
operator?
Here's the underlying struct for 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;
I'm not sure wheter this statement could throw an segmentation fault
It won't seg fault. It is in fact a typical application of short-circuit logical operators.
And is it the same for while loop conditions?
Yes.
Short circuit evaluation is not a property of if-condition or while-condition. It is the property of the expression itself. It is still short circuit even if it is not used as a condition.
For example, this is still short-circuited:
bool x = frame != NULL && frame->data != NULL;
And is it the same for the || operator?
Yup. It is also short circuit.
Well, not exactly. OR relation get it short-circuited when the first part is TRUE. That is not exactly the same as AND.