Inspired by a program described in K&R section 5.5:
void strcpy(char *s, char *t)
{
while(*s++ = *t++);
}
C program
if ('\0') { printf("\'\\0\' -> true \n"); }
else { printf("\'\\0\' -> false\n"); }
if ("\0") { printf("\"\\0\" -> true \n"); }
else { printf("\"\\0\" -> false\n"); }
prints
'\0' -> false
"\0" -> true
Why do '\0'
and "\0"
evaluate differently in C?
clang version 3.8.0
Recall how string literals work in C - "\0"
is a character array containing two zero bytes (the one you asked for, and the implicit one at the end). When evaluated for the if
test, it decays into a pointer to its first character. This pointer is not NULL, so it's considered true when used as a condition.
'\0'
is the number zero, equivalent to just 0
. It's an integer which is zero, so it's considered false when used as a condition.