Variables in C++



In this tutorial, we will learn about variables in C++ language. We will cover the basics of declaring and using variables, including naming conventions.


What are Variables

Variables in C++ are used to store data values that can be manipulated during program execution. They have a data type that determines the kind of data they can hold, such as integers, characters, or floating-point numbers.


Naming Variables

When naming variables in C++, follow these conventions:

  • Start with a letter (either uppercase or lowercase) or an underscore (_).
  • Subsequent characters can include letters, digits, or underscores.
  • Avoid using reserved keywords as variable names.
  • Use meaningful and descriptive names to enhance code readability.

Syntax

The syntax to declare variables in C++ is:

data_type variable_name;


Example 1: Variable storing Integer Value

  1. Declare an integer variable named num.
  2. Assign a value of 10 to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>

int main() {
    // Declare and initialize an integer variable
    int num = 10;
    // Print the value of the variable
    std::cout << "The value of num is: " << num << std::endl;
    return 0;
}

Output

The value of num is: 10


Example 2: Variable storing Character Value

  1. Declare a character variable named letter.
  2. Assign the character 'A' to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>

int main() {
    // Declare and initialize a character variable
    char letter = 'A';
    // Print the value of the variable
    std::cout << "The value of letter is: " << letter << std::endl;
    return 0;
}

Output

The value of letter is: A


Example 3: Variable storing Floating-Point Value

  1. Declare a floating-point variable named pi.
  2. Assign the value 3.14 to the variable.
  3. Print the value of the variable.

C++ Program

#include <iostream>

int main() {
    // Declare and initialize a floating-point variable
    float pi = 3.14;
    // Print the value of the variable
    std::cout << "The value of pi is: " << pi << std::endl;
    return 0;
}

Output

The value of pi is: 3.14