简体   繁体   中英

Use ptrdiff_t or size_t for indexing

I got into the habit of declaring for loop indices with size_t instead of int . That however already bit me multiple times when I was iterating an array backwards, ie checking for the index to be greater or equal to zero:

for (size_t i = n-1; i >= 0; i--) {
    // ...
}

When the body has been run for i == 0 , it gets decremented and wraps around, to SIZE_T_MAX probably. That makes the break condition a tautology. There might be some clever bit manipulations to check for possible underflows, but wouldn't it be simpler to use ptrdiff_t instead?

What is the proper idiomatic C way to solve this? size_t plus bit twiddling or ptrdiff_t and feeling uncomfortable about semantics?

A backwards loop should look like this:

for (size_t i = 0; i != n; ++i) {
    arr[n - i - 1] = foo();
}

The n - i - 1 is the "reverse iterator" corresponding to i , if you will.

Here is a safer way to write your downward loop:

  • it works with both signed or unsigned index types,
  • it uses the array length unmodified just once. You could also write i = sizeof(arr) / sizeof(*arr) if arr is defined as an array.
  • i takes all valid index values in decreasing order.
for (size_t i = n; i-- > 0;) {
    arr[i] = compute_value(i);
}

One could write i --> 0 as an eye catcher idiom, but some experts seem to disagree on this alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM