How to Declare Variables in C++
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, the value of x is 1 until the program changes the value to something else. References to x are replaced by the value 1.
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, is of type int, and has the value 10; and that a variable y of type int also exists with the value 5. You can declare variables (almost) anywhere you want in your program — as long as you declare the variable before you use it.