for loop termination

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
#include <cctype>

using namespace std;

int main()
{
	int i;
	char str[80] = "This Is A Test";

	cout << "Original string: " << str << "\n\n";

	for (i = 0; str[i]; i++)
	{
		if (isupper(str[i]))
			str[i] = tolower(str[i]);
		else if (islower(str[i]))
			str[i] = toupper(str[i]);
	}

	cout << "Inverted string : " << str << "\n\n";
	return 0;
}
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.
Hello DonnaPin,

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.

Andy
OK I think I am understanding now, going to try out a few other loops to try and make sure i get it. Thank you both for the answers
Topic archived. No new replies allowed.