what is range checking in c?

3.9k Views Asked by At

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?

2

There are 2 best solutions below

10
On BEST ANSWER

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.

3
On

On Windows, you can often say system("pause") to make the environment wait for you to press enter, provided that you have #included stdlib.h. However, you should be aware of the following:

  • It is not considered anywhere near good practice to rely on the presence of a pause.exe command in the current environment. It may be true on most Windows systems, but is generally not true on Unices or Macs. So you would be limiting your otherwise portable program to a single platfom.

  • You may want to consider why you want the user to press enter. Most people think it's good if programs do their work and then just exit. It's very uncommon for "real" programs to wait for user confirmation in this manner. If you just want to see what the DOS prompt says before it closes itself, perhaps thie problem lies with the DOS prompt rather than with your program?

I remember asking this same question when I started out with programming, but I have since realised that pausing programs is the Wrong Thing in most cases.