• Post Reply Bookmark Topic Watch Topic
  • New Topic

Assign a range to an integer variable  RSS feed

 
Sanjeev Mehta
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there some way I can assign a fixed range to a variable.
For example, can I fix the range of variable i to 0 to 255 such that



I want this to return me i as 255 and not 260. Is there some way I can achieve this rounding?
Thanks
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why not just write a quick and dirty method that will clamp the int to the range -- at the time that you call it?

Henry
 
Sanjeev Mehta
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I could do that. Was just wondering if there was another way to go about it.
Thanks
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Primitive types have no notion of "ranges". (Neither to the default objects that represent the primitives.) Unlike Ada we can't simply define native-looking types, allow operator overloading to act on them, and so on.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David Newton wrote:Primitive types have no notion of "ranges".

Except for the absolute minimum and maximum values (e.g. Integer.MIN_VALUE and Integer.MAX_VALUE).

Sanjeev, check out Math.max and Math.min.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, yeah, but we're talking about substantially smaller numbers here.
 
Ulrika Mingle
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sanjeev Mehta wrote:
I want this to return me i as 255 and not 260. Is there some way I can achieve this rounding?


Sure, you can design your own type.

You introduce a class called RangeInt256 or something and give it properties you want.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!