tags:

views:

120

answers:

4

Is the following going to work as expected on all platforms, sizes of int, etc? Or is there a more accepted way of doing it? (I made the following up.)

#define MAX_NON_NEGATIVE_INT ((int)(((unsigned int)-1) / 2))

I won't insult your intelligence by explaining what it's doing!

Edit: I should have mentioned that I cannot use any standard classes, because I'm running without the C runtime.

+4  A: 

If you don't want to use defines (and you want a standard way of calculating the limits), then do this:

#include <limits>
std::numeric_limits<int>::min()

These are the ANSI standard defines in limits.h:

#define INT_MIN     (-2147483647 - 1) /* minimum (signed) int value */
#define INT_MAX       2147483647    /* maximum (signed) int value */
#define UINT_MAX      0xffffffff    /* maximum unsigned int value */

These are the defines from BaseTsd.h:

#define MAXUINT     ((UINT)~((UINT)0))
#define MAXINT      ((INT)(MAXUINT >> 1))
#define MININT      ((INT)~MAXINT)
Mark Ingram
I'm running VS2005 and MAXINT isn't defined anywhere in the headers! The closest in BaseTsd.h is MAXINT_PTR, but no banana. However, the _PTR versions I do have do almost the same as the above. More importantly, the above does exactly what my original define does except it does ">> 1" where I do "/ 2". The only difference is that I've mangled the MAXINT and MAXUINT together!
Sam
These are the wrong macros: http://tigcc.ticalc.org/doc/limits.html Also since this is a C++ question you should lead with numeric_limits
Martin York
Thanks Martin, I've updated the answer to reflect this.
Mark Ingram
A: 
#include <climits>


INT_MAX
Anders K.
+11  A: 

There is a standard way to this:

#include <limits>
#include <iostream>

cout << numeric_limits<unsigned int>::max();

Being standard, this is guaranteed to be portable across all platforms.

Péter Török
You should note that `numeric_limits` will not give you constant expression. So you can't write, for instance, `enum X { x1 = std::numeric_limits<unsigned int>::max() };`.
Kirill V. Lyadvinsky
A: 

You can have a look at the class numeric_limits, included in the standard library.

See here.

Luca Martini