3

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 ?

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158

1 Answers1

2

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.

Community
  • 1
  • 1
aaronman
  • 18,343
  • 7
  • 63
  • 78
  • We learn Pascal in our school,not c++,and in Pascal you can write : type natNo=0..999; var x:natNo; for example. I thought you could do something like that in C++ too. –  Aug 03 '13 at 15:08
  • I'm not too familiar with pascal but you cannot do this in c++ with out some work, as you can see I have now started the class for you to make it work just like an int you will have to overload all the operators – aaronman Aug 03 '13 at 15:12
  • Just know I really only just started it there is quite a bit more work to do – aaronman Aug 03 '13 at 15:14
  • Check out the link I posted it's a more complete version of what I started – aaronman Aug 03 '13 at 15:19
  • I would upvote you,but I dont have enough reputation,so sorry about that. –  Aug 03 '13 at 15:27
  • you can still accept :) there is no rep requirement to accept. and eventually you will get enough rep to upvote – aaronman Aug 03 '13 at 15:28