Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop including pointer

Tags:

c++

pointers

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.

like image 546
Vanguard827 Avatar asked Mar 05 '26 07:03

Vanguard827


1 Answers

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.

like image 59
Bartek Banachewicz Avatar answered Mar 07 '26 22:03

Bartek Banachewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!