• Home
  • 1.6 Variable Initialization

1.6 Variable Initialization

View Categories

1.6 Variable Initialization

< 1 min read

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 variable age and initializes it with the value 21.
  • float temperature = 36.5f; initializes a floating-point variable with a float literal. The f suffix specifies that the literal is of type float.
  • 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::cout statement retrieves the value stored in the corresponding variable and writes it to the standard output stream.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *