Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does dereferencing occur only once in this while loop in C/C++? [closed]

Tags:

c++

c

Why is *str in the following fragment dereferenced only once? It takes the first character of the string 'a' and keeps incrementing this value until it reaches the end of the ASCII table, contrary to my expectation of dereferencing it on every condition evaluation and resulting in the infinite loop. This behavior does change even if the dereference is moved from the condition to the body of the loop. GCC version 7.4.0 was used to test the code.

int getLen(char *str){
    int count=0;
    while((*str)++) {
        count++;
    }
    return count;
}

int main(){
    char s[]="abc";
    printf("length is %d\n",getLen(s));
}

Output: 159

like image 463
user1602 Avatar asked Oct 24 '19 05:10

user1602


3 Answers

It is dereferenced 159 times, not just once.

The ASCII value of a is 97. If you increment that 159 times, you get 0.

(*str)++ doesn't increment str, it increments the first character in str.

It doesn't increase it "until it reaches the end of the ASCII table", it increases until it becomes 0. If your char type is signed, that means that it increments it to the maximum of that type, then from the minimum (a negative value) up to 0.

Typically, char is signed and 8-bits. In that case, it will increase to 127, the next value will be -128 and after that it will keep increasing until it becomes 0.

If you want to use parentheses for clarity, use

while (*(str++)) 
{
    count++;
}

That is the same as

while (*str++)
{
    count++;
}
like image 127
Sid S Avatar answered Oct 15 '22 17:10

Sid S


The term (*str)++ is the source of your problem. You have added () around *str, which makes sure that *str is evaluated first and that value is incremented. It never increments str. Use *str++ instead.

while(*str++) {
    count++;
}
like image 20
R Sahu Avatar answered Oct 15 '22 19:10

R Sahu


The expression (*str)++ says, dereference str first, then increment the dereferenced value. It never increments str itself (the pointer). So, to answer your question, it's not that str is being dereferenced only once, it's dereferenced every time in the loop, but it never gets incremented hence the dereferenced memory is same every time.

like image 30
rogme Avatar answered Oct 15 '22 18:10

rogme