Kapol
Kapol

Reputation: 6463

How does this loop work?

I wanted the below loop to increment the pointer until encountering the null-terminating character. It doesn't work correctly, though.

while (*s++ != '\0')
    ;

This one does:

while (*s != '\0')
    s++;

I can't seem to understand what is the difference between the two.

This question is related to exercise 5.3 of The C Programming Language book.

Upvotes: 1

Views: 135

Answers (4)

CalebB
CalebB

Reputation: 607

The "++" is an increment operator which functions very similar to "s += 1" or "s = s + 1" although ++ does increment s by 1, position of the operator will effect the outcome. Observe below:

int  x;
int  y;

// Increment operators
x = 1;
y = ++x;    // x is now 2, y is also 2
y = x++;    // x is now 3, y is 2

The difference is in whether you want to increment the value to be set "pre"(Before) or post(after) evaluation(retrieval of the value).

Upvotes: 0

Natan Streppel
Natan Streppel

Reputation: 5866

while (*s++ != '\0')
    ;

The above statement will increase the value of s whether (*s++ != '\0') returns false or true. If false, it will increment it as well, but it will break out of the loop anyway.

while (*s != '\0')
    s++;

The above statement won't increase the value of s if (*s != '\0') returns false, then breaking out of the loop, making so that *s still keeps pointing to '\0'.

Upvotes: 7

glglgl
glglgl

Reputation: 91017

Hint: When happens the ++ in both cases, and when doesn't it? Especially in the last loop run?

Let's have a look: In the last loop run, the expression between () is evaluated.

In the first example, this means the ++ is executed, having s point after the NUL byte.

In the second example, there is no ++ in the (), and the loop body isn't executed any longer. So ++ does not happen, having s point to the NUL byte.

Upvotes: 4

2501
2501

Reputation: 25752

The difference is the state of the pointer after the loop.

In the first example you point one after the 0 character, and in the second you point at the 0 character.

Upvotes: 7

Related Questions