Table of Contents
Variables can be initialized at the time they are declared. Initialization assigns an initial value before the variable is used, reducing the possibility of working with uninitialized data.
This example demonstrates direct initialization of variables and their use in a C++ program.
Source Code #
#include <iostream>
int main()
{
int age = 21;
float temperature = 36.5f;
char grade = 'A';
std::cout << "Age: " << age << '\n';
std::cout << "Temperature: " << temperature << '\n';
std::cout << "Grade: " << grade << '\n';
return 0;
}
Output #
Age: 21
Temperature: 36.5
Grade: A
Explanation #
int age = 21;declares the variableageand initializes it with the value21.float temperature = 36.5f;initializes a floating-point variable with afloatliteral. Thefsuffix specifies that the literal is of typefloat.char grade = 'A';initializes a character variable with the character'A'.- Initialization combines declaration and assignment into a single statement.
- A variable initialized during declaration is ready for use immediately after it is created.
- Each
std::coutstatement retrieves the value stored in the corresponding variable and writes it to the standard output stream. return 0;terminates the program successfully.