It is important to remember that str is not really a "string", but rather a pointer in the memory cell where the char (part of the string) is stored.
Next, we need to understand how the compiler sees all these elements. Let's look at their types:
str is of type char * (literally, "pointer to char ")NULL - null pointer constant (at least in my system, ((void*)0) )'\0' is a character constant (it really has an int type, but don't worry about it, it is usually used in a context that requires a char value)
See * in char * and void * ? This tells the compiler that these are pointer types (which is a fancy way of saying that variables of this type don't matter, they just point to it). Therefore, when the compiler sees char *str , it knows that you can ask to do something like *str or str[0] (they both do the same). We will come back to this later.
You see, when you write str in a C program, the compiler knows that a variable called "str" ββis stored in a memory location, for example, 0x0001. The generated code goes to 0x0001 and gets the value. That way, if you do something like
str + 1
Then the compiler will generate code that looks something like this:
fetch the value from where str is stored (0x0001) add 1 to that value
What I'm sure you know. So, it should now be obvious what this line says:
str == NULL
Since NULL is the constant of a null pointer, this line checks if str null pointer (that is, a pointer that does not point to anything).
Therefore, the compiler usually generates code as follows:
fetch the value from where str is stored check if that value is 0
Remember, if you like, we told the compiler that str really a pointer type. Therefore, we are allowed to write this:
*str
And this makes the compiler generate this:
fetch the value from where str is stored now use that value as a memory address and fetch what is stored there
So, if str held 0x0200, we get the value from the memory address 0x0200. Note that the compiler doesn't care if the string is actually stored there.
(I assume that you know that str[0] matches *str . This simplifies the explanation of what is happening.)
How about this?
*str == '\0'
So this line is valid:
*str == (char) 0
This causes the compiler to generate this:
fetch the value from where str is stored now use that value like a memory address and fetch the char that is stored there check if the value of that fetched char is 0
Summarizing:
- The spelling
str == NULL indicates whether the str pointer is specified . - Writing
*str == '\0' indicates whether the str pointer points to an empty string (in fact, pointing to a memory location with zero).
(A "string" is by definition a "continuous sequence of characters ending with and including the first null character", so if the very first character of a string is '\0' , then the string is an empty string.)