int limits for C programming

chipy

Golden Member
Feb 17, 2003
1,469
2
81
hi all,

merry christmas!! to the point: i'm trying to learn C programming.

when reading books or online tutorials i keep coming across that the maximum value of a "signed int" is 32767.

however, when i try programming code and assign a value greater than 32767, like 7000000, to an int variable, i can still assign my number even though books/tutorials say otherwise.

i noticed they also mention that it differs from computer to computer. how do i find out what the maximum limit is on my computer OR

if i am approaching the concept the wrong way please show me the right way.

merry christmas,
chipy
 

igowerf

Diamond Member
Jun 27, 2000
7,697
1
76
Have you tried printing out the value of the int? I doubt it'll show you 7000000. When you try to put too high of a value in the integer, it will overflow.

EDIT: Actually, 7000000 will print out just fine. In Windows, ints should be 4 bytes, so it can be up to 2147483647.
 

chipy

Golden Member
Feb 17, 2003
1,469
2
81
igowerf,

thanks for the reply. yes, as part of my program i did try to print of the value of the variable. it did print our that number.

on a similar note, i used "sizeof" on int/short int such as follows: sizeof(int)

and it told me 4 bytes.
if i am not mistaken, 4 bytes == 32 bits.
doest this mean anything to my original question?

thanks,
chipy

P.S. Keep the comments coming :)



 

igowerf

Diamond Member
Jun 27, 2000
7,697
1
76
Actually, now that I look at it, 7,000,000 should print out just fine. In Windows, ints are 4 bytes so they can go up to 2,147,483,647.
 

chipy

Golden Member
Feb 17, 2003
1,469
2
81
thanks for your help.

btw, how did you come up with 2,147,483,647?

thanks,
chipy
 

igowerf

Diamond Member
Jun 27, 2000
7,697
1
76
It's 2^31 - 1... Hmm.... You should probably read up on this, if you want to understand it better.

EDIT: Basically, the int can hold 2^32 values since it's a 32 bit integer. That means half are negative and half are positive, thus we have 2^31-1 (excluding 0) positive numbers and -2^31 negative numbers.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Most likely, the source you're reading is a little out of date. In C, the size of an int depends on the machine's architecture (or the mode the CPU is in), and it used to be that an int was 16 bits, giving you 0 to 64k (unsigned) or -32k to 32k (signed). Now, most compilers use 32 bits for ints, giving you either -2 billion to 2 billion, or 0 to 4 billion.
 

chipy

Golden Member
Feb 17, 2003
1,469
2
81
Thanks to CTho9305 and BingBongWongFoeey for the information!

I now have another question which I will post after this.

Chipy