-2

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.

electro103
  • 147
  • 6

1 Answers1

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