Namespaces
Variants
Actions

Variables

From cppreference.com
Revision as of 08:10, 21 September 2013 by 188.97.193.163 (Talk)


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.

Contents

Creation

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

int x;

This is a declaration statement, which declares the variable x to be 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.

You cannot re-declare another variable with the same name in the same scope.

Using Variables

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.

An assignment operation will copy the value on right hand side to the variable on the left hand side. These variables will still be independent after the operation. In the following example y will retain its original value:

x = y;
x = 5;

Using uninitialized Variables

C++ strictly outlaws reading uninitialized variables as “undefined behavior”. However, this does not imply, that compilers will prevent you from doing this:

int z;
y = z * 2;

The C++-standard imposes no requirements of any kind on this program. Not only is the value of y and z completely unpredictable, but both the compiler and the created executable are allowed to erase your hard drive, although of course no sane compiler will do such a thing.

Still, make sure that all variables are initialized correctly and listen carefully to compiler-warnings.

On the other hand it is perfectly legal, though questionable, to let a variable uninitialized and assign a value to it later:

int z;
z = 3;

Overview

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";
 
    // int x = y; // error: x was already declared
    x = y;
    std::cout << "x: " << x << "\n";
 
    x = x + 1;
    std::cout << "x: " << x << "\n";
 
    int z;
    // std::cout << "z: " << z << "\n"; // disallowed
 
    z = 3;
    std::cout << "z: " << z << "\n";
}

Possible output:

x: 6
y: 14
x: 14
x: 15
z: 3