Variables
Location
-
Courses
/
-
Quick C course
/
Variables
What is a variable?
A variable is simply a memory space. It has a type, specifying its size and what kind of data it can represent, and a name, used to refer to it.
Defining a variable
Here we define a variable of type int and named 'var':
int var;
Note the semicolon. In C, all instructions are ended by a semicolon.
Primitive types
The primitive types are the basic variable types.
They are divided in 3 groups:
Primitive group | Represents |
---|---|
Integer | Positive and negative integer numbers. |
Unsigned integer | Positive integer numbers. |
Floating-point | Positive and negative numbers (May have digits after the decimal point). |
The only difference between the types inside a same group is their size in bytes. The bigger it is, the wider the range of numbers it can represent is.
The only types with a fixed size are char and unsigned char. They weight 1 byte. The size of the other types may vary depending on the compiler used (The program that translates the code into binary code).
Here are the variable types of the integer group (From the smallest to the biggest), with a possible size and range of numbers they can represent (Only there as an example):
Primitive | Size (In bytes) | Range of number |
---|---|---|
char | 1 | [-128, 127] |
short int | 2 | [-32768, 32767] |
int | 4 | [-2147483648, 2147483647] |
long int | 4 | [-2147483648, 2147483647] |
long int int | 8 | [-9223372036854775808, 9223372036854775807] |
The same for the unsigned integer group:
Primitive | Size (In bytes) | Range of number |
---|---|---|
unsigned char | 1 | [0, 255] |
unsigned short int | 2 | [0, 65535] |
unsigned int | 4 | [0, 4294967295] |
unsigned int long | 4 | [0, 4294967295] |
unsigned int long long | 8 | [0, 18446744073709551615] |
Note that the keyword int is optional (Except for the type int itself), so 'unsigned int' is equivalent to simply 'unsigned' and 'short int' is the same as 'short'.
The floating-point group:
Primitive | Size (In bytes) |
---|---|
float | 4 |
double | 8 |
double long | 16 |
Note that a variable of floating-point type can represent huge numbers. However, when the amount of digits increases, the precision lowers and the number becomes approximated. That way, the number 123456789 could become 123456792. This is however often not a problem. It does not matters so much if a character moves 8.000005 meters per second or 8.000002...
Naming variables
The name of variables (And all other things) may not contain spaces nor symbols (Like %). It may contain digits, but not as the first character.
Valid:
int name_of_a_variable123;
Invalid:
int 5invalid%;