Variables in C++ Programming



Definition of C++ variables

Variables represent storage locations in the computer’s memory. Constants are data items whose values cannot change while the program is running. Variables allow you to store and work with data in the computer’s memory.

Example of a C++ program with a variable:
 
    // This program has a variable.
    #include <iostream>
    using namespace std;
    int main()  {
    int number;
    number = 5;
    cout << "The value of number is " << "number" << endl;
    cout << "The value of number is " << number << endl;
    number = 7;
    cout << "Now the value of number is " << number << endl;
    return 0;    }                       
     
 
    Output:
    The value of number is number
    The value of number is 5
    Now the value of number is 7                       
     

Variable Assisments and Initialization

An assignment operation assigns, or copies, a value into a variable. You have also seen that it is possible to assign values to variables when they are defined. This is called initialization.

When multiple variables are defined in the same statement, it is possible to initialize some of them without having to initialize all of them.

In C++ terminology, the operand on the left side of the = symbol must be an lvalue that identifies a place in memory whose contents may be changed.

The program below illustrates this.
 
    // This program shows variable initialization.
    #include <iostream>
    #include <string> 
    using namespace std;
    int main()  {
    string month = "February"; month is initialized to "February"// 
    int year, // year is not initialized
    days = 28; // days is initialized to 28
    year = 2007; // Now year is assigned a value
    cout << "In " << year << " " << month
    << " had " << days << " days.\n";
    return 0;   }          
     
 
    Output:
    In 2007 February had 28 days.                       
     

Variables scope

A variable’s scope is the part of the program that has access to the variable. The scope of a variable is the part of the program where it may be used.The first rule of scope is that a variable cannot be used in any part of the program before it is defined.

 
    // This program can't find its variable.
    #include <iostream>
    using namespace std;
    int main()  {
    cout << value; // ERROR! value has not been defined yet!
    int value = 100;
    return 0;   }
     
     

PROMOTIONS