Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - pointer arithmetic

Tags:

c

pointers

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.

like image 739
sherrellbc Avatar asked Feb 14 '26 08:02

sherrellbc


2 Answers

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.

like image 91
Aniket Inge Avatar answered Feb 16 '26 21:02

Aniket Inge


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'.

like image 38
lulyon Avatar answered Feb 16 '26 21:02

lulyon