Vanguard827
Vanguard827

Reputation: 31

for loop including pointer

I tried to output a string "Hello" using pointer. Here is the code

char s[] = "Hello";  
char * p;
for( p = s; p[0]; ++ p )     
    cout << * p;
return 0;

I don't understand why p[0] in the for loop can work.

Upvotes: 3

Views: 92

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39400

p[0] is exactly equivalent to *p in this case. It will evaluate to '\0' at the end of your array, which means a numerical value of 0, which then gets converted to a value of false and stops the loop.

Upvotes: 10

Related Questions