AS for your last question,
But why does not NULL work?
Usually, NULL
is a pointer type. Here, myText[counter]
is a value of type char
. As per the conditions for using the ==
operator, from C11
standard, chapter 6.5.9,
One of the following shall hold:
- both operands have arithmetic type;
- both operands are pointers to qualified or unqualified versions of compatible types;
- one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or
- one operand is a pointer and the other is a null pointer constant.
So, it tells, you can only compare a pointer type with a null pointer constant ## (NULL
).
After that,
When (or how) does while(myText[counter])
evaluate to false?
Easy, when myText[counter]
has got a value of 0
.
To elaborate, after the initialization, myText
holds the character values used to initialize it, with a "null" at last. The "null" is the way C identifies the string endpoint. Now, the null, is represented by a values of 0
. So, we can say. when the end-of-string is reached, the while()
is FALSE.
Additional explanation:
while(myText[counter] != '\0')
works, because '\0'
is the representation of the "null" used as the string terminator.
while(myText[counter] != 0)
works, because 0
is the decimal value of '\0'
.
Above both statements are equivalent of while(myText[counter])
.
while(myText[counter] != EOF)
does not work because a null is not an EOF
.
Reference: (#)
Reference: C11
standard, chapter 6.3.2.3, Pointers, Paragraph 3
An integer constant expression with the value 0
, or such an expression cast to type void *
, is called a null pointer constant.
and, from chapter, 7.19,
NULL
which expands to an implementation-defined null pointer constant
Note: In the end, this question and realted answers will clear the confusion, should you have any.