I want to define maximum of a char in my program to 5. Is it a way to achieve this without controlling each time with 5.
Asked
Active
Viewed 97 times
-2
-
1So you want to limit the memory assigned to an `int` or `char` to 3 bits? – Arc676 Dec 24 '15 at 07:54
-
1The `char` type can't be changed, if you want to *clamp* some value to a specific range you have to do it yourself. – Some programmer dude Dec 24 '15 at 07:58
-
@Arc676 Yes, in a some way – electro103 Dec 24 '15 at 07:58
-
3No you can't. Representations of numbers use bits and, at least in C, you can only limit the number of bits of a given variable (see bit fields in structures), so the maximum value that you can obtain is always 2^n-1 for a given n. – Jean-Baptiste Yunès Dec 24 '15 at 07:59
-
See [here](http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm) for limiting the memory available to variables in `struct`s – Arc676 Dec 24 '15 at 08:00
-
I totally disagree with down votes, this is a very natural question for a beginner. – Jean-Baptiste Yunès Dec 24 '15 at 08:10
1 Answers
3
No you can't. Representations of numbers use bits and, at least in C, you can only limit the number of bits of a given variable (see bit fields in structures), so the maximum value that you can obtain is always 2^n-1 for a given n. This way :
struct small {
int limited:5; // 5 bits variable
};
int main() {
struct small s;
for (s.limited=0; ; s.limited++) {
printf("%d\n",s.limited);
}
}
Of course you can change the type to unsigned
if needed.
If you want to control the bounds for a given variable, you need to define functions or macros to do it, for example:
#define SET(x,v) { if (v>5) abort(); (x) = (v); }
...
int a;
SET(a,4);
...
SET(a,45);
There is other possibilities as using opaque types to ensure that enforcing a bad value is nearly impossible but it is slightly more difficult.

Jean-Baptiste Yunès
- 34,548
- 4
- 48
- 69