-1

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?

  • And how can i force evaluating all values in an if-statement (even if i check 3 variables)

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;
Michael Gierer
  • 401
  • 2
  • 6
  • 15
  • 1
    http://en.cppreference.com/w/cpp/language/operator_logical and probably a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) – Passer By Feb 24 '18 at 13:18
  • 3
    Checking if pointer is not null and then && to access its method in the same expression is perfectly fine, but your while loop does the opposite – Killzone Kid Feb 24 '18 at 13:22
  • As far as I know, short circuit evaluation behaves the same in C and C++. – Jesper Juhl Feb 24 '18 at 13:23
  • Can you clarify what do you mean by "force evaluating all values"? –  Feb 24 '18 at 13:26
  • In modern C++ it is preferred to compare pointers against `nullptr` instead of `NULL`. https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr – Jorge Y. Feb 24 '18 at 13:30

1 Answers1

3

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.