Don1
Don1

Reputation: 3

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

Upvotes: 0

Views: 1849

Answers (2)

Mark Elliot
Mark Elliot

Reputation: 77044

If flag_val != NULL evaluates to false, that is, flag_val is NULL, then short circuit logic will stop the evaluation of the rest of the expression (since the entire condition cannot be true). What you're doing is fine.

Upvotes: 1

cdhowie
cdhowie

Reputation: 169018

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.

Upvotes: 8

Related Questions