Jacob
Jacob

Reputation: 475

Is pointer valid condition for a loop?

Can someone carefully explain, why in this case for loop repeats 10 times?

#include <iostream>
using namespace std;
int main(){ 
    int length=-1;
    char s[]="Bad or nice";//10 characters 

    for ( char *q = s; *q; ++q ){
    cout << *q;
    length++;
    }

    cout << "\n" << length;

return 0;
}

Upvotes: 0

Views: 205

Answers (2)

mstrthealias
mstrthealias

Reputation: 2921

The condition is the value at the memory location of the pointer (*q).

Therefore the loop terminates when the NULL character is reached (at the end of the string), which is evaluated as false.

Upvotes: 3

haccks
haccks

Reputation: 106122

Total characters in the string is 11 excluding \0. Second for expression *q becomes false when q points to last character of the string s, which is \0.
Therefore, loop repeats 11 times. You are getting 10 output because you initialized length with -1.

Upvotes: 4

Related Questions