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.
3 Answers 3
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.
2 Comments
while(*p++); return (p- s -1);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円'.
Comments
In the first case:-
while(*p++ != '0円');
p will be incremented just after the evaluation of an expression irrespective of whether the condition is true or false because ++ is a part of conditional expression.
Whereas, in the second one:-
while(*p != '0円') p++;
First the condition will be checked and if it is true then only p will be incremented.
3 Comments
++p would do the increment before the comparison. But in the first case, the increment is executed even if the string is zero length.*p contains 0円 or not. If it does, p++ is incremented in the second snippet. Whereas, p will be incremented regardless of if the condition where true or false in the first snippet.
i++and++i?int i = 3, j = 3; printf("%d, %d\n", ++i, j++);.