Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL check for nested pointers in a single if-statement

Tags:

c

if-statement

Struct {
    int a;
    struct sample *b;
} test;

int func(struct test *t1) {
  if (!t1 || !t1->b) {  // Is this statement ok?
    return _EINVAL
  }

  ...
}

Is it ok to NULL check for nested pointers in a single if-statement? Can I always assume that the left check(!t1 in my example) will be performed first?

like image 387
Sandeep Avatar asked Nov 23 '25 05:11

Sandeep


1 Answers

Yes, the language rules of C guarantee that if the expression a in a || b is true, then b is never evaluated. (A similar rule exists for a && b if a evaluates to false.) This is called short-circuit evaluation.

like image 51
Greg Hewgill Avatar answered Nov 24 '25 21:11

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!