0

As there are min() and max() functions in C++, what is the equivalent in C to find the range of an unknown type?

If unknown (e.g. "ctype") where nothing about the implementation is known, how would go about getting the MIN and MAX of this number?

2 Answers2

3

If it's an unsigned arithmetic type, you can do (ctype)-1, which is guaranteed to evaluate to the maximum value ctype can hold (and the minimum value then of course is 0).

Otherwise, if no assumption about the type or the implementation can be made, you can't know for sure.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
2

One simple way is to use sizeof to get the size in bytes, multiply by 8 to get the number of bits, and then work from that. Though that doesn't make a difference between signed and unsigned.

However I suggest you instead search through the header files used by your program to find out what the type really is.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I can see that working for a max. For a min, how would you adjust for the asymmetry and - value? Would it just be -(sizeof(type) * BIT_COUNT) –  Jul 22 '14 at 11:05
  • 1
    How do you know that in a particular implementation all `int`s with the high bit set are a trap representation, so the range is halved? – Matteo Italia Jul 22 '14 at 11:07