- What Is a Variable?
- Defining a Variable
- Assigning Values to Variables
- Using Type Definitions
- Constants
- Summary
- Q&A
- Workshop
- Activities
Assigning Values to Variables
A variable is assigned a value using the = operator, which is called the assignment operator. The following statements show it in action to create an integer named highScore with the value 13,000:
unsigned int highScore; highScore = 13000;
A variable can be assigned an initial value when it is created:
unsigned int highScore = 13000;
This is called initializing the variable. Initialization looks like assignment, but when you work later with constants, you'll see that some variables must be initialized because they cannot be assigned a value.
The Rectangle program in Listing 3.2 uses variables and assignments to compute the area of a rectangle and display the result.
Listing 3.2. The Full Text of Rectangle.cpp
1: #include <iostream> 2: 3: int main() 4: { 5: // set up width and length 6: unsigned short width = 5, length; 7: length = 10; 8: 9: // create an unsigned short initialized with the 10: // result of multiplying width by length 11: unsigned short area = width * length; 12: 13: std::cout << "Width: " << width << "\n"; 14: std::cout << "Length: " << length << "\n"; 15: std::cout << "Area: " << area << "\n"; 16: return 0; 17: }
This program produces the following output when run:
Width: 5 Length: 10 Area: 50
Like the other programs you've written so far, Rectangle uses the #include directive to bring the standard iostream library into the program. This makes it possible to use std::cout to display information.
Within the program's main() block, on line 6 the variables width and length are created and width is given the initial value of 5. On line 7, the length variable is given the value 10 using the = assignment operator.
On line 11, an integer named area is defined. This variable is initialized with the value of the variable width multiplied by the value of length. The multiplication operator * multiplies one number by another.
On lines 13–15, the values of all three variables are displayed.