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
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing. In C language it is generally used to mark an end of a string.
The \0 is treated as NULL Character. It is used to mark the end of the string in C. In C, string is a pointer pointing to array of characters with \0 at the end.
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The null character '\0' (also null terminator ), abbreviated NUL , is a control character with the value zero . Its the same in C and objective C. The character has much more significance in C and it serves as a reserved character used to signify the end of a string ,often called a null-terminated string.
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.
First of all, you need to keep in mind that in C,
NULL
is false and non-NULL
is true.'\0'
, as others have said, is the same as the integer literal 0
and hence is false (See first bullet point above to know why).
"\0"
is a string literal that contains two \0
characters (One which you have explicitly added and the other, which is implicit and will be added by the compiler). The string literal will be stored somewhere in read-only memory. When you use "\0"
, it gets converted to a pointer to its first element†. This is commonly referred to as "array decay". (This is the reason why stuff like char* str = "string";
works).
So, you are effectively checking the address of the first character of the string literal. Since the address of the string literal will always be non-NULL
, the if will always be true (See second bullet point above to know why).
†: This "decay" of arrays does not always happen. See Exception to array not decaying into a pointer?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With