简体   繁体   中英

while sentinel variable with post-increment operator

what's the difference between:

while(*s++ != '\0') {}

and

while(*s != '\0') {
   s++;
}

s is a char * . The latter works OK. but at the end of first loop, *s is not equal to '\\0' .

In case of

 while(*s++ != '\0') {}

the increment is done as a post increment operator, in the condition-check statement itself. In this case, the value change (increment) is the side effect after the value computation for the operator. Thus, after the value is used (in comparison), s gets incremented.

On the other hand,

while(*s != '\0') {
   s++;
}

the increment takes place as post-increment inside the conditional block, which will only execute if the condition is TRUTHY. Once the condition is evaluated to be false, s is not incremented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM