Reputation: 1204
What is the reason for this? I thought that if a pointer is null then the rest of the condition won't be evaluated.
// doesn't work:
char *ptr = somefunction();
if (ptr && ptr[0] == '1' || ptr[0] == 't')
// ...
// does work:
char *ptr = somefunction();
if (ptr)
if (ptr[0] == '1' || ptr[0] == 't')
// ...
Upvotes: 1
Views: 112
Reputation: 183
You have Null ptr && dereferenced Null ptr which causes seg fault.
C gives you the option to have statements like if (ptr == NULL) do something; If it always evaluated a condition to false when a null pointer was detected statements like this wouldn't work.
Upvotes: 1
Reputation: 63600
ptr && ptr[0] == '1' || ptr[0] == 't'
means:
ptr && ptr[0] == '1'
(false, because ptr
is null and ptr[0] == '1'
doesn't get evaluated)ptr[0] == 't'
(boom)Use:
ptr && (ptr[0] == '1' || ptr[0] == 't')
instead.
Upvotes: 5
Reputation: 46892
&&
has higher precedence than ||
so the code is equivalent to:
if ((ptr && ptr[0] == '1') || ptr[0] == 't')
and if the first (...&&..)
fails, then the second half of ||
is evaluated.
Upvotes: 3
Reputation: 29579
Your order of evaluation is incorrect. This will work:
if (ptr && (ptr[0] == '1' || ptr[0] == 't'))
Basically, any time you have both &&
and ||
in your code, you need a parentheses in there to ensure it does what you mean it to.
Upvotes: 1