Variables#
C is a statically typed programming language and so the data type of every variable must be known at compile-time.
A variable must be declared before it can be used:
data-type variable_name;
Multiple variables of the same data type can also be declared on the same line by listing their names separated by commas:
data-type variable1, variable2, ...;
Names of variables can only contain uppercase and lowercase letters, underscores and numbers, but cannot begin with a number. They also can't be reserved keywords like for, char, etc.
The first time a value is assigned to a variable is known as its initialization:
int var; // Declaration
var = 2; // Initialization
Declarations and initializations can also be combined on a single line:
double pi = 3.14, e = 2.72; // Declaration and initialization
If a variable is declared in one file but it is initialized in another, its declaration must be marked with the extern keyword:
// other.cpp
double pi = 3.14;
// main.cpp
extern double pi; // extern tells the compiler to look for the initialization of pi in the other files
double double_pi = pi * 2;