Search code examples
cnullstrcmp

C - conditional statement & strcmp & NULL string


How safe would be to do something like:

if (flag_val != NULL && strcmp (val, flag_val) == 0) {
   // something
} else {
   // something else
}

Knowing that sometimes flag_val will be NULL and sometimes not.

I know it will check first if flag_val != NULL, if it evaluates false, it shouldn't check the second condition right?

Thanks


Solution

  • Correct, if flag_val is NULL then the && operator will short-circuit. As long as flag_val can't be changed by some other thread, this is safe code.