Skip to main content

Section 3.6 Printing Variables

You can display the current value of a variable by using cout. The following statements declare a variable named answer, assign it the value 42, and display that value:
Listing 3.6.1.
When we talk about displaying a variable, we generally mean the value of the variable. To display the name of a variable, you have to put it in quotes:
Listing 3.6.2.
Printing out a variable’s name and value can be very helpful for debugging. For example, if you have a variable totalPay that holds the total pay for a week, you could print it out like this:
cout << "totalPay is now " << totalPay << endl;
As the program runs, it will print out the current value of totalPay so that we can examine the output and see what value the variable had at that point.
Recall that to output multiple values on the same line, you can either use one cout that outputs multiple values (each separated by <<) or you can use multiple cout statements. This program demonstrates two different ways to print 11:59.
Listing 3.6.3.

Checkpoint 3.6.1.

What prints when the following code is run?
int main() {
  int a;
  int b;
  a = 2;
  b = 8;
  cout << "a";
}
  • The string, not the variable, a will be printed.
  • b will not be printed.
  • The cout statement prints a, not the value of the variable a.
  • 8 is the value of b and will not be printed
  • Nothing! There will be a compile error!
  • Try again.

Checkpoint 3.6.2.

Now, what prints?
int main() {
  int a;
  int b;
  a = 2;
  b = 8;
  cout << b;
}
  • The string a will not be printed.
  • The string b will not be printed.
  • 2 is the value of a will not be printed.
  • 8 is the value of b and will be printed!
  • Nothing! There will be a compile error!
  • Try again.
You have attempted of activities on this page.