user2560703
user2560703

Reputation:

How do I set an integer's interval?

I know this is a very noob-ish question,but how do I define an integer's interval?

If I want an integer X to be 56<= X <=1234 , how do I declare X ?

Upvotes: 3

Views: 2783

Answers (1)

aaronman
aaronman

Reputation: 18750

The best way would be to create your own integer class with bounds on it and overloaded operators like +, * and == basically all the ops a normal integer can have. You will have to decide the behavior when the number gets too high or too low, I'll give you a start on the class.

struct mynum {
    int value;
    static const int upper = 100000;
    static const int lower = -100000;
    operator int() {
        return value;
    }
    explicit mynum(int v) {
        value=v;
        if (value > upper)value=upper;
        if (value < lower)value=lower;
    } 
};
mynum operator +(const mynum & first, const mynum & second) {
   return mynum(first.value + second.value);
}  

There is a question on stackoverflow already like your question. It has a more complete version of what I was doing, it may be a little hard to digest for a beginner but it seems to be exactly what you want.

Upvotes: 2

Related Questions