Hello, I am currently going over a conversion of a string to upper/lower case using a for loop. The book states that "the loop iterates until the null terminating str is indexed. Since null is zero the loop ends" which I believe I understand - the string has a null at the end so the loop ends. But I do not understand why it actually ends. From what ive seen the expression part in the for loop usually says something like 'i < 10', like an expression that has something to be checked against. But with this null terminating loop, it just seems to be a zero, so im lost at why that actually stops the loop.
I hope I have explained myself well enough with this, if anyone could help me understand why this works, it would be appreciated.
for (i = 0; str[i]; i++)
is equivalent to: for (i = 0; str[i] != 0; i++)
char str[80] = "This Is A Test"; copies the string literal into the str array, and the last character of a string literal is implicitly a null character, whose value is 0.
What you need to understand first is whether it is an if statement a for loop condition or a while loop condition each will eventually evaluate to something that is convertible to a bool type result of (0) zero false or (1) true.
So when the for condition is i < 10 and say the "i" is 1 then 1 < 10 is true and the loop continues. When "i" reaches 10 then the condition evaluates to false.
In Ganado's first example he is using a shorthand which is saying that if the value of "str[i]" is not zero, i.e., considered true, then the loop continues, but if the value should be zero or "\0" or "NULL" then the condition becomes false.