The int Data Type

Prev: The char Data Type
Next: The float and double Data Types
and the sizeof Operator



The int Data Type

Variables of the int data type represent whole numbers. If you try to assign a fraction to an int variable, the decimal part is ignored and the value assigned is rounded down (or TRUNCATED) from the actual value.

Also, assigning a character constant to an int variable assigns the ASCII value.

#include <stdio.h>
int main() {
  int a,b,c,d,e;
  a = 10;
  b = 4.3;
  c = 4.8;
  d = 'A';
  e = 4.3 + 4.8;
  
  printf("a = %d\n", a);
  printf("b = %d\n", b);
  printf("c = %d\n", c);
  printf("d = %d\n", d);
  printf("e = %d\n", e);
  printf("b+c = %d\n", b+c);
  
  return 0;
} 

The output of the example is:

a = 10
b = 4
c = 4
d = 65
e = 9
b+c = 8

Obviously, 10 gets assigned to a without any problems.

4.3 gets rounded down to 4 when assigned to b.

4.8 gets rounded down to 4 when assigned to c - not up to 5 as one may have expected.

Now, d gets assigned 65 - the ASCII code for the character 'A'.

9 gets assigned to e because 4.3+4.8 equals 9.1, which gets rounded down.

The first 5 printf statements prints out the integer values of a through to e.

The last printf statement prints out the sum of b and c, that is, 4 and 4 and not 4.3 and 4.8.



The signed and unsigned Keywords

When you declare a variable of the type, int, by default, its value is SIGNED. In other words, the variable could be positive or negative.

On my machine, the minimum value of a signed int is -32768 and the maximum value is 32767 (that is, 215-1).

An unsigned int on the other hand, can only store positive values, and has the range from 0 to 65535 (that is, 216-1).

To declare an unsigned int variable you simply type the unsigned keyword in front of the int keyword, like this:

unsigned int x;



The short and long Keywords

The cases above all apply when the integer is of the short type, which takes up less memory than the long type. The range of values that a short int could store is somewhat limited, so if you're planning to store huge numbers you'd want to use the long type.

Most of the time, an integer with be of the signed short type by default, which is why you've never seen me declare a signed short int.

Here's a summary:

Type

Minimum Value

Maximum Value

signed short int

-32768

32767

unsigned short int

0

65535

signed long int

-2147483648

2147483647

unsigned long int

0

4294967295

Note that:

215 = 32768
216 = 65536
231 = 2147483648
232 = 4294967296



Prev: The char Data Type
Next: The float and double Data Types
and the sizeof Operator

www.iota-six.co.uk Copyright © 2001-2003
Unauthorized copying not permitted

Designed and Developed Using Macromedia Studio MX