Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 627
Ahmad Badoura Avatar asked Jan 21 '23 04:01

Ahmad Badoura


1 Answers

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

like image 79
AnT Avatar answered Jan 31 '23 09:01

AnT