Namespaces
Variants
Actions

intro/variables

From cppreference.com
Revision as of 16:54, 11 September 2013 by P12 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Variables

A variable in most general definition is a named chunk of data. They directly correspond to a piece of memory somewhere on the computer. A variable holds a single value all the time, which can be modified, replaced, or used in other computations.

In C++, all variables must be declared before use. For example:

int x;

This is a declaration statement, which declares a variable of type int (integer). Such variable can hold integer values, such as -100, 0], 1, 10, etc.

What the above statement did behind the scenes is to instruct the compiler to reserve some memory and refer all usages of the variable to that piece of memory.

Once the variable is declared (the memory is reserved), it can be used in a variety of ways. For example, it can be assigned a value:

x = 10;

Now the variable holds a value of 10. This value can be used in computations, for example:

int y;
y = x * 5;

A newly declared variable y now holds a value of 50. The above can be written in a shorter way, for example int y = x * 5;. This is equivalent to the above code.

It's possible to use a variable before the variable is assigned a value. For example:

int z;
y = z * 2;

This will lead to bugs in your program. Here's why: z holds indeterminate (unknown) value just upon declaration. It's not possible to know what the value is. It may be 0 on one run of the program, or 100 or any other value on the other. If z is used in any computations, they will lead to unpredictable results. Therefore, make sure all variables are assigned values before the first use.

The example below shows various ways how variables can be used:

#include <iostream>
 
int main()
{
    int x = 6;
    std::cout << "x: " << x << "\n";         // print the value of x
 
    int y = x * 2 + 2;
    std::cout << "y: " << y << "\n";
 
    x = y;
    std::cout << "x: " << x << "\n";
 
    x = x + 1;
    std::cout << "x: " << x << "\n";
 
    int z;
    std::cout << "Unpredictable value: " << z << "\n";
}

Possible output:

x: 6
y: 14
x: 14
x: 15
z: 5090194