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')
// ...
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.