Lesson 2.5. Variables initialization

Syntax

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.

Uninitialized variable

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.

Quiz

How to declare several variables on the same line?

Check Bravo! Remember that the instructions are separated by a semicolon. Try again...

How to initialize a variable on the same line as its declaration?

Check Bravo! The first solution is more elegant, it should be preferred. Try again...

How to declare an integer and a float in the same instruction?

Check Bravo ! You can't declare two variables of different types simultaneously. Try again...

What value will an uninitialized variable have?

Check Bravo! The variable will take the previous value of the memory where it is stored. Try again...

**What does the following program display?

int zero;
printf ("%d", zero);
Check Bravo! You can never predict the value of an uninitialized variable. It is better to avoid this type of program. Try again...

See also


Last update : 10/23/2022