Is It Possible to Limit a Datatype Range in C

485 views Asked by At

My question is about to limit the maximum range of a datatype so as to not exceed it is maximum value. For example:

 unsigned char var1;

In this case minimum value for var1 is 0, maximum value for var1 is 255.

In my case for var1 200-255 are reserved value so it is necessary not to enter these values for safety reasons.

My question, is there any implementation method for C in order to limiting primitive data types range.

Thanks.

1

There are 1 answers

2
John Bode On

The philosophy behind C is that the programmer is in the best position to know whether a range check needs to be performed, and is smart enough to write it if necessary. There is nothing in the standard library that will do this for you.

You can write a simple macro for the test (easier than typing in the actual expression, and it sort of documents exactly what you're doing):

#define RANGE_CHECK(val,lo,hi) ((lo) <= (val) && (val) <= (hi)) // inclusive range check

and invoke it as necessary:

if ( RANGE_CHECK( x, 0, 200 ) )
  // do something with x
else
  // range violation, handle as necessary.  

This is extremely primitive, but should at least point you in the right direction. If you need to do this for floating point, you'll want something way more robust.