Chapter 2. Declaring Variables Constantly

In This Chapter

  • Declaring variables

  • Declaring different types of variables

  • Using floating-point variables

  • Declaring and using other variable types

The most fundamental of all concepts in C++ is the variable— a variable is like a small box. You can store things in the box for later use, particularly numbers. The concept of a variable is borrowed from mathematics. A statement such as

x = 1

stores the value 1 in the variable x. From that point forward, the mathematician can use the variable x in place of the constant 1 — until he changes the value of x to something else.

Variables work the same way in C++. You can make the assignment

x = 1;

From that point forward in the execution of the program, until the value of x is changed, the value of x is 1. References to x are replaced by the value 1. In this chapter, you will find out how to declare and initialize variables in C++ programs. You will also see the different types of variables that C++ defines and when to use each.

Declaring Variables

A mathematician might write something like the following:

(x + 2) = y / 2
x + 4 = y
solve for x and y

Any reader who's had algebra realizes right off that the mathematician has introduced the variables x and y. But C++ isn't that smart. (Computers may be fast, but they're stupid.)

You have to announce each variable to C++ before you can use it. You have to say something soothing like this:

int x;
x = 10;

int y;
y = 5;

These lines of code declare that a variable x exists, ...

Get C++ For Dummies®, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.