Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Eraserhead

macrumors G4
Original poster
Nov 3, 2005
10,434
12,250
UK
A quick question

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

Thanks
 

Gelfin

macrumors 68020
Sep 18, 2001
2,165
5
Denver, CO
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);
}
 

Gelfin

macrumors 68020
Sep 18, 2001
2,165
5
Denver, CO
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);
}
 

iSee

macrumors 68040
Oct 25, 2004
3,540
272
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;
}
 

Gelfin

macrumors 68020
Sep 18, 2001
2,165
5
Denver, CO
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.)

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. :)

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.
 

Eraserhead

macrumors G4
Original poster
Nov 3, 2005
10,434
12,250
UK
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.