Variables

Location
  1. Courses

    /

  2. Quick C course

    /

  3. 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 groupRepresents
IntegerPositive and negative integer numbers.
Unsigned integerPositive integer numbers.
Floating-pointPositive 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):

PrimitiveSize (In bytes)Range of number
char1[-128, 127]
short int2[-32768, 32767]
int4[-2147483648, 2147483647]
long int4[-2147483648, 2147483647]
long int int8[-9223372036854775808, 9223372036854775807]

The same for the unsigned integer group:

PrimitiveSize (In bytes)Range of number
unsigned char1[0, 255]
unsigned short int2[0, 65535]
unsigned int4[0, 4294967295]
unsigned int long4[0, 4294967295]
unsigned int long long8[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:

PrimitiveSize (In bytes)
float4
double8
double long16

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%;