post decrement in while conditon in C
I've done a search and I’ve found nothing relevant to my query. I am currently debugging a C optimizer and the code in question looks like this:
while( x-- )
array[x] = NULL;
What should happen in this instance? And should the result of this logic be consistent across all compilers?
Lets say that the initial value of x in this case is 5.开发者_如何转开发
The problem is that the program crashes, my understanding is that it is caused by a negative array element reference.
Any help would be appreciated.
This cycle will end with x
equal to -1
(assuming x
is signed), but its body will not produce access to array[-1]
at the last step. The last array access is to array[0]
. The behavior is consistent across all implementations.
In other words, there's no problem with negative index array access in the code you quoted. But if you attempt to access array[x]
immediately after the cycle, then you'll indeed access array[-1]
.
The code you quoted is a variation of a fairly well-known implementational pattern used when one needs to iterate backwards over an array using an unsigned variable as an index. For example
unsigned x;
int a[5];
for (x = 5; x-- > 0; )
a[x] = 0;
Sometimes less-experienced programmers have trouble using unsigned indices when iterating backwards over an array. (Since unsigned variables never have negative values, a naive implementation of the cycle termination condition as x >= 0
does not work.) This approach - i.e. post-increment in the cycle termination condition - is what works in such cases. (Of course, it works with signed indices as well).
If the initial value of x
is 5, it will execute:
array[4] = NULL;
array[3] = NULL;
array[2] = NULL;
array[1] = NULL;
array[0] = NULL;
If x
is a signed type, then the final value of x
will be -1
; otherwise, it will be the maximum value of the type.
Make sure x
is non negative before processing the while
loop(precondition).
Also x
value will be -1 when the process leaves the while
loop(post condition). Therefore, after leaving while
loop, you should not access the array
using x
as index.
精彩评论