In the The Traditional First Program I talked about the main() function returning an integer to the operating system. int is a datatype. In C, there are a few basic datatypes. Before I talk about those, I’ll explain a bit about computers and memory.
The smallest piece of memory in a computer is called a bit. Bit stands for binary digit. In the binary number system there are only two numbers: 0 and 1. So, a bit is like a switch that the computer can turn on and off. The next relevant memory size is called a byte. In a sense, this is really the basic size that computer programs work with. A byte is 8 bits and can contain 256 different values.
From a byte we get kilobyte (KB), megabyte (MB), gigabyte (GB), etc. A KB is 1024 bytes. A MB is 1024 KB (1,048,576 bytes). A GB is 1024 MB (1,073,741,824 bytes).
The basic datatypes in C are as follows with the number of bytes used in ():
char (1) a single character
short (2) a whole number between -32768 and 32767
int (2 or 4 depending on processor – on intel and similar processors it is 4)
long (4) a whole number between -2,097,154 and 2,097,153
float (4 on intel and similar processors) a floating point decimal value where min and max values depend on processor
double (8) a double precision float. A double will hold a wider range of values than a float but it’s primary use is to provide more precise calculations.
Also, all datatypes except the float and double can have the keyword unsigned placed in front of them. What this means is that they only hold positive numbers. For example, and unsigned short can have values between 0 and 65,535.
If I want to create an integer in a program to use to store a whole number value of a high score, I would do it like this:
If I wanted to give it a starting value of 0, I would do this:
You’ll see some examples of datatype usage in the next tutorial.