59 points · by mv9 · 5y ago · 12 comments
Also for further reading see much of John Regehr's blog, e.g. [Taming Undefined Behavior in LLVM][1].
One thing that I find artificial in the examples is to use signed integers for loops. I always have seen unsigned integers in practice. In general I try to avoid signed integers like plague for big values storage and only use them for error propagation, with negative values for errors like the libc does.
Also, I don’t know whether it (¿still?) is valid C, but I’ve used negative indexes in the past in graphics applications, where it is convenient to have an 'array' with indices that dont start at zero. One-dimensional example:
#define N 100
char a[2 * N + 1];
char * b = a + 100;
...
for(int x = -N; x <= N; ++x) b[x] = 42;Functions like isprint(int c), which checks whether c is a printable ASCII character, can take as input numbers between -128 and 127 or between 0 and 255.
To achieve this, implementations usually rely on single array indexable from -128 to 255 (a lookup table).
Example from the newlib: https://sourceware.org/git/?p=newlib-cygwin.git;a=blob;f=new...
And the array came (indirectly) from: https://sourceware.org/git/?p=newlib-cygwin.git;a=blob;f=new...
I think that in Rust the unsigned types do not wrap by default, so that the compiler does not have to introduce these checks at runtime. If one wants wrapping, they have to directly use the wrap types instead which would be more instruction-heavy.
I wonder if there is a way in C to reproduce this mechanism in order to not generate any check instructions as well for unsigned types.