Ali
Ali

Reputation: 10453

When is the condition of this for loop will becomes false?

I'm working on my C++ practice question to prepare for my upcoming test and I'm struggling with a for loop condition that I have never seen before.

        for (int i = 0; s[i]; i++)

The string s that has been sent from the main is "Two roofs to fix"

The question is when is the for loop's condition will become false?

Upvotes: 1

Views: 172

Answers (3)

Mitch Wheat
Mitch Wheat

Reputation: 300579

The loop condition becomes false, when the string's terminating zero '\0' is hit. (if (0) evaluates to false)

Please note: this form of test is a possible error waiting to happen if the string isn't null terminated.

Upvotes: 5

wyx
wyx

Reputation: 59

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s = "Two roofs to fix";
    int i;
    for (i = 0; s[i]; i++);
    cout<<"i = "<<i<<endl;
}

I test the problem with the above code. It returns an error "string subscript out of range". So if the length of string s is Len, s[Len] is illegal. In your code, s is not a pointer char*, but a string. So it is unappropriate to code like this.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490178

Just to clarify @MitchWheat's answer, if an expression used as a condition specifies only a value, like if (x), then it's essentially equivalent to if (x != 0). If the value is a pointer type, then it's equivalent to if (x != NULL) instead (though that's not really an "instead", since NULL == 0).

Upvotes: 2

Related Questions