Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Variables in C++

A variable lets a program store and refer to data of a particular type. Learn declarations, initialization, assignment, the roles of auto and const, and the distinction between a name's scope and an object's lifetime.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

int count{3};
int zero{};
auto total = count + 2;
const int limit{10};
count = 4;

A variable in C++ is introduced by a declaration of an object or reference, subject to exceptions specified by the standard. In the typical declaration int count{3};, the name count denotes an object of type int, initialized to 3. A reference can bind to an object or a function; the reference itself is not an object and does not hold a copy of what it refers to.

Initialization gives an object its initial value when it is created; assignment changes an existing object's value. Thus, int count = 3; is initialization, whereas a later count = 4; is assignment. The declaration int count{3}; uses list-initialization, which prohibits narrowing conversions such as in int count{3.5};. The declaration int zero{}; initializes an integer to zero. An ordinary local declaration int zero; without static does not initialize its value—do not read it before giving it a value.

In auto total = count + step;, the compiler deduces the type int; auto does not allow the variable's type to change later. total receives the computed value, so changing count later does not recalculate total. The declaration const int step{2}; creates an object that must not be modified; ordinary assignment to step is a compilation error.

Scope determines where a name can be used, while lifetime determines when an object exists; these are not interchangeable concepts. The ordinary local variable names in the example can be used from their declarations to the end of the block, and their objects exist from completion of initialization until the block is exited. The eel.is source is an evolving working draft, not a frozen C++23 publication; the constructs presented here are available in C++23.

Examples

#include <iostream>

int main() {
    int count{3};
    const int step{2};
    auto total = count + step;
    count = 4;
    int zero{};

    std::cout << count << ' ' << total << ' ' << zero << '\n';
}

Result

4 5 0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources