# [SOLVED] Minimum C int value

Discussion in 'Mac Programming' started by Eraserhead, Jun 15, 2007.

Joined:
Nov 3, 2005
Location:
UK
#1
A quick question

How to you get the minimum value for int programmatically in C/Obj-C?

Thanks

2. ### Gelfin macrumors 68020

Joined:
Sep 18, 2001
Location:
Denver, CO
#2
I'm fairly certain there's a more optimal and less ugly way to do this, but this will accomplish what you need, and it's the first thing that sprung to mind. Note that this will be accurate whether int is 32 or 64 bits wide.

Code:
```#include <stdio.h>
void main(void)
{
int nMin = 8;
unsigned int* pMin = (unsigned int*)&nMin;
while(0 != (*pMin << 4)) *pMin <<= 4;
printf("INT_MIN: %d\n", nMin);
}
```

3. ### Gelfin macrumors 68020

Joined:
Sep 18, 2001
Location:
Denver, CO
#3
Here's an enhanced version that calculates everything you might want to know about local integers:

Code:
```#include <stdio.h>
void main(void)
{
int nMin = 8;
int nMax = 0;
int nWidth = 8;
while(0 < (nMin <<= 4)) nWidth += 4;
nMax = nMin^-1;
printf("Integers on your system are %d bits wide.\n", nWidth);
printf("The maximum integer is %d.\n", nMax);
printf("The minimum integer is %d.\n", nMin);
}```

4. ### iSee macrumors 68040

Joined:
Oct 25, 2004
#4
You could use this snippit:
Code:
`1 << (sizeof(int) * 8 - 1)`
But it's probably better to #include <limits.h> and use INT_MIN

(as far as I know, limits.h and INT_MIN are cross-platform.)

here's a little test program:
Code:
```#include <stdio.h>
#include <limits.h>

int main(int argc, char* argv[])
{
printf("%d %d\n", 1 << (sizeof(int) * 8 - 1), INT_MIN);
return 0;
}
```

Joined:
Nov 3, 2005
Location:
UK
#5
That's exactly what I wanted, brilliant!

6. ### gnasher729 macrumors P6

Joined:
Nov 25, 2005
#6
... and I have seen compilers where this will give you a value of +32768, while INT_MIN had a value of -2,147,483,648.

7. ### Gelfin macrumors 68020

Joined:
Sep 18, 2001
Location:
Denver, CO
#7
Well, first off I assumed "programmatically" meant "calculate it," but second, check /usr/include/limits.h before you make any assumptions. I checked that first, and you'll be surprised.

Ah, never mind. They buried it down in i386/limits.h. Just had to crawl through all the nested includes to find it. This'll work.

8. ### lazydog macrumors 6502a

Joined:
Sep 3, 2005
Location:
Cramlington, UK
#8
I think this will also work it gives the same result as INT_MIN anyway.

Code:
```int minlimit = (int)( ( ( (unsigned int) -1 ) >> 1 ) + 1 ) ;
```

b e n

Joined:
Nov 3, 2005
Location:
UK
#9
The numbers are all going to be fairly reasonable with what I am doing, (really 0 to 10 or so) so even -32000 would be OK here.