As other answers have explained, the basic answer is that any expression that evaluates to 0 gets interpreted as a 'false' condition in C or C++, and *s
will evaluate to 0 when the s
pointer reaches the null termination character of the string ('\0').
You could equivalently use the expression *s != 0
, and some developers might argue that this is what should be used, giving the opinion that the 'fuller' expression is more clear. Whether or not you agree with that opinion, you need to be able to understand the use of the terse alternative, since it's very commonly used in C/C++ code. You'll come across these expressions a lot, even if you prefer to use the more explicit comparision.
The more rigorous explanation from the standard (for some reason I feel compelled to bring this into the discussion, even though it doesn't really change or clarify anything. In fact, it probably will muddle things unnecessarily for some people - if you don't care to get into this level of trivia, you'll miss absolutely nothing by clicking the back button right now...):
In C, the *s
expression is in what the standard calls 'expression-2' of the for
statement, and this particular for
statement example is just taking advantage of the standard's definition of the for
statement. The for
statement is classified as an 'iteration statement', and among the semantics of any iteration statement are (6.8.5/4 "Iteration statements"):
An iteration statement causes a statement called the loop body to be executed repeatedly
until the controlling expression compares equal to 0.
Since the 'expression-2' part of the for
statement is the controlling expression, this means that the for
loop will execute repeatedly until *s
compares equal to 0.
The C++ standard defines things a little differently (but with the same result). In C++, the for
statement is defined in terms of the while
statement, and the condition part of the while
statement controls the the iteration (6.5.1/1 "The while statement"):
until the value of the condition becomes false
Earlier in the C++ standard, the following describes how expressions are converted to bool
(4.12 "boolean conversions"):
An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true
Similar wording in the standard (in both languages) apply to the controlling expression/condition of all selection or iteration statements. All this language-lawyerese boils down to the fact that if an expression evaluates to 0 it's the same as evaluating to false (in the English sense of the word, since C doesn't have a built-in false
keyword).
And that's the long, confusing explanation of the simple concept.