my_question
my_question

Reputation: 3255

What is the difference between these code snippets?

I have the following code snippet running great:

char* head = str;
char* tail = head;
while ( *tail ) {
    ++tail;
}

I changed the while loop for simplification and the new code is

char* head = str;
char* tail = head;
while ( *tail++ );

I believe the above 2 code snippets work same. But the 2nd one does! In GDB I see that, for a string with 32 characters, pointer tail is 33 larger than head which should be 31.

I am really baffled.

Upvotes: 2

Views: 175

Answers (4)

Vladislav Reshetnyak
Vladislav Reshetnyak

Reputation: 321

For the second one you need to provide a condition that you want it to apply, otherwise you'll get those side effects.

Maybe throw in a do at the end?

Upvotes: 0

Why baffled?

The increment is conditional in the first case and unconditional in the second.

The second form is probably less useful (because you have to decrement to get back to the terminator), but should be OK as you are allowed to compute (but not dereference) addresses one past the end of a allocation.

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75150

The first one will check if *tail is not 0, and if it is not 0, increment tail. If it is 0, it will stop the loop before incrementing tail.

The second one will increment tail then check if the old value of tail points to 0. If not, it will continue. If so, it will stop, but notice that it has already incremented tail.

So basically the difference is the first one will leave tail pointing to a 0, while the second will leave tail pointing to the character after the 0.

Upvotes: 0

StilesCrisis
StilesCrisis

Reputation: 16320

For the second piece of code, the post-increment occurs whether or not *tail evaluates to zero.

Upvotes: 6

Related Questions