crange-checking

what is range checking in c?


While I'm reading some C tutorials, I found this line which I do not understand:

C Lacks range-checking

What does that mean?

Another small question: how can I pause code to not terminate quickly after finishing? I think we say System("PAUSE") or some thing like that. How can I make it in C?


Solution

  • It means that you can define operations whose logical result is outside of the range of values allowed for the type. e.g.

    unsigned char a = 0xFF;
    unsigned char b = a + 1;
    

    The compiler will very happily allow this, and return a result of 0x00. 0xFF + 1 overflows the one byte storage of a. Notice that 0x00 is just the low-order 8 bits of the correct answer '0x100`. This can be repaired with:

    unsigned char a = 0xFF;
    unsigned b = (unsigned)a + 1;
    

    which first makes more room for the value in a by converting it to a larger integer type and saving it to a larger type.

    A similar issue is bounds checking in which the compiler will happily let you write:

    int a[5] = {1, 2, 3, 4, 5};
    i = 1000;
    b = a[i];
    

    (EDITED based on the comments:) After executing this code, an exception will likely be thrown, but the compiler doesn't care at all.