Iterating an array backward in C using an unsigned index -
is following code, safe iterate array backward?
for (size_t s = array_size - 1; s != -1; s--) array[s] = <do something>; note i'm comparing s, unsigned, against -1;
is there better way?
this code surprisingly tricky. if reading of c standard correct, code safe if size_t @ least big int. case because size_t implemented unsigned long int.
in case -1 converted size_t (the type of s). -1 can't represented unsigned type, apply modulo arithmetic bring in range. gives size_max (the largest possible value of type size_t). similarly, decrementing s when 0 done modulo size_max+1, results in size_max. therefore loop ends want end, after processing s = 0 case.
on other hand, if size_t unsigned short (and int bigger short), int represent possible size_t values , s converted int. in other words, comparison done (int)size_max != -1, return false, breaking code. i've never seen system happen.
you can avoid potential problems using size_max (which provided <stdint.h>) instead of -1:
for (size_t s = array_size - 1; s != size_max; s--) ... but favorite solution this:
for (size_t s = array_size; s--; ) ... wiki
Comments
Post a Comment