There are several ways to declare and initialize variables:
Simple declaration
float x;
Declaration and initialization
float x=8.5;
Declaration, then initialization
float x;
x=8.5;
Declaration of several variables
float x, y, z;
Declaration and initialization of several variables. This is the most popular solution. One usually tries to group together similar or related variables.
float x=8.5, y=-3.2, z;
Note that the last variable z
is not initialized.
Consider the following program. What does it display?
float x;
printf ("%f", x);
One would naturally think that the program would display zero and this will often be the case, but unfortunately ... not always! This makes the uninitialized variables a particularly devious problem, since it will work most of the time.
An uninitialized variable will take the value previously stored in the same memory location. This will often be zero, but not always. The variables used without being initialized is a problem that causes many bugs that are difficult to diagnose. This phenomenon has a dedicated Wikipedia page.
How to declare several variables on the same line?
How to initialize a variable on the same line as its declaration?
How to declare an integer and a float in the same instruction?
What value will an uninitialized variable have?
**What does the following program display?
int zero;
printf ("%d", zero);