Understanding C++/Variables

From Wikibooks, open books for an open world
Jump to navigation Jump to search

A variable is a symbolic name that represents and can be used in place of a value. Variables are used similarly to how letters in algebra are sometimes used in place of numbers (such as x=14, x+2=16). However unlike algebra variables names in C++ are not limited to single letters and values are not limited to just numbers. Variables can make programming easier because what "3.14159" is supposed to mean may not be as easy to figure out as what "pi" means.

The basics of variable use goes something like this:

int x = 14;
int a = 4;
int myint = a * a;

cout << myint;
cout << x * 2;
cout << x * a;


Output:

16
28
56


We see the variables x, a, and myint being declared, or given values, in the first three lines. Variables can be declared as values, like 14 or 4, other variables, which gives them the same values, or expressions using other variables, which gives them the value of the simplified expression. The "cout <<" section tells the program to output what comes after. An output function can output a single variable, which gives the value of the variable, or an expression, which gives the value of the simplified expression.

Three things are important to note. One, because this code will not compile or run correctly on a normal compiler, it is known as "pidgin code". Many examples are given in pidgin code for ease of understanding. Two, the only variable type used here is the "int" type, but there are two other major variable types: string and boolean. We will cover those later. Lastly, in C and C++, the "=" operation does not do what it would seem to do. It sets the first half of the expression to whatever the second half evaluates to. When a program checks whether two numbers are equal, it uses the "==" operator.