C++ Variables

A variable can hold any data of a certain data type. For example, an integer variable (int) can hold any integer but only integers - no decimals, strings, etc. The exact value held by the variable can change while the program runs. Only the variable type cannot change. You the programmer declares the variables needed for a given program. You give each variable any name you choose. When you declare a variable, you must decide what type of variable it is according to the kind of data it will hold.Here are the most commonly used variable types:

C++ Code Meaning
int whole numbers (integers)
long very large integers
float numbers with decimals
char single characters
string character strings (i.e. words)


You declare a variable as follows:

     int myNumber;

The line above declares a variable called myNumber of type int or integer.You can assign a value to the variable with the assignment operator - = - as follows:

     myNumber = 8;

The variable to which a value is being assigned always goes on the left of the assignment operator, its new value on the left. You can display the value contained my the variable using cout. The following code in a program:


     int main()
     {
          int myNumber;
          myNumber = 8 ;
          cout << "\nMy number is " <<  myNumber;
          cin.get();
          return 0;
     }

will be

My number is 8

You can assign a value to the variable from the keyboard by using the cin operator. During the run of a program the value assigned to a variable can change.

In the program below we get a value from the keyboard and assign it to the variable and display the variables value to the screen. Then we assign a new value to the variable and display the new value to the screen.



     int main()
     {
          int myNumber;
          cout << "\nPlease enter my number: ";
          cin >> myNumber;
          cout << "\nMy number is " << myNumber << ".\n";
          myNumber = myNumber * 2;
          cout << "Twice my number is " << myNumber << ". \n";
          cin.get();
          cin.get();
          return 0;
     }