In the following code:
int strlen(char *s){
char *p = s;
while(*p++ != '\0');
return p - s;
}
Why does the above evaluate differently than this:
int strlen(char *s){
char *p = s;
while(*p != '\0') p++;
return p - s;
}
It is my understanding that the expression will evaluate first, and then increment.
in the first code p is incremented regardless of if the while() condition was true or false.
In the second snippet of code, p is incremented ONLY if while condition was true.
Consider the last step in while loop when *p = '\0'.
In 1st code:
while(*p++ != '\0');
p still get one increment, and pointer to the element behind '\0'.
In 2nd code:
while(*p != '\0') p++;
*p != '\0' is not true, so while loop end, p get no increment. p pointer to '\0'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With