Initialization - cppreference.com (2024)

C++ language

General topics
Flow control
Conditional execution statements
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous

Initialization of a variable provides its initial value at the time of construction.

The initial value may be provided in the initializer section of a declarator or a new expression. It also takes place during function calls: function parameters and the function return values are also initialized.

Contents

  • 1 Initializers
    • 1.1 Initializer semantics
  • 2 Non-local variables
    • 2.1 Static initialization
    • 2.2 Dynamic initialization
    • 2.3 Early dynamic initialization
    • 2.4 Deferred dynamic initialization
  • 3 Static local variables
  • 4 Class members
  • 5 Notes
  • 6 Defect reports
  • 7 See also

[edit] Initializers

For each declarator, the initializer (if exists) may be one of the following:

= expression (1)
= {}
= { initializer-list }
= { designated-initializer-list }
(2)

(since C++20)

( expression-list )
( initializer-list )
(3) (until C++11)
(since C++11)
{}
{ initializer-list }
{ designated-initializer-list }
(4) (since C++11)
(since C++11)
(since C++20)

1) Copy-initialization syntax.

2) Aggregate initialization syntax.(until C++11)List-initialization syntax.(since C++11)

3) Direct-initialization syntax.

4) List-initialization syntax.

expression - any expression (except unparenthesized comma expressions)
expression-list - a comma-separated list of expressions (except unparenthesized comma expressions)
initializer-list - a comma-separated list of initializer clauses (see below)
designated-initializer-list - a comma-separated list of designated initializer clauses


An initializer clause may be one of the following:

expression (1)
{} (2)
{ initializer-list } (3)
{ designated-initializer-list } (4) (since C++20)

Syntaxes (2-4) are collectively called braced-enclosed initializer list.

[edit] Initializer semantics

If no initializer is specified for an object, the object is default-initialized. If no initializer is specified for a reference, the program is ill-formed.

If the initializer specified for an object is () (cannot appear in declarators due to the syntax restriction), the object is value-initialized. If the initializer specified for a reference is (), the program is ill-formed.

The semantics of initializers are as follows:

  • If the entity being initialized is a reference, see reference initialization.
  • Otherwise, the entity being initialized is an object. Given the type of the object as T:
  • If the initializer is of syntax (2):
(until C++11)
(since C++11)
#include <string>std::string s1; // default-initializationstd::string s2(); // NOT an initialization! // actually declares a function “s2” // with no parameter and returns std::stringstd::string s3 = "hello"; // copy-initializationstd::string s4("hello"); // direct-initializationstd::string s5{'a'}; // list-initialization (since C++11)char a[3] = {'a', 'b'}; // aggregate initialization // (part of list initialization since C++11)char& c = a[0]; // reference initialization

[edit] Non-local variables

All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function begins (unless deferred, see below). All non-local variables with thread-local storage duration are initialized as part of thread launch, sequenced-before the execution of the thread function begins. For both of these classes of variables, initialization occurs in two distinct stages:

[edit] Static initialization

There are two forms of static initialization:

1) If possible, constant initialization is applied.

2) Otherwise, non-local static and thread-local variables are zero-initialized.

In practice:

  • Constant initialization is usually applied at compile time. Pre-calculated object representations are stored as part of the program image. If the compiler doesn't do that, it must still guarantee that the initialization happens before any dynamic initialization.
  • Variables to be zero-initialized are placed in the .bss segment of the program image, which occupies no space on disk and is zeroed out by the OS when loading the program.

[edit] Dynamic initialization

After all static initialization is completed, dynamic initialization of non-local variables occurs in the following situations:

1) Unordered dynamic initialization, which applies only to (static/thread-local) class template static data members and variable templates(since C++14) that aren't explicitly specialized. Initialization of such static variables is indeterminately sequenced with respect to all other dynamic initialization except if the program starts a thread before a variable is initialized, in which case its initialization is unsequenced(since C++17). Initialization of such thread-local variables is unsequenced with respect to all other dynamic initialization.

2) Partially-ordered dynamic initialization, which applies to all inline variables that are not an implicitly or explicitly instantiated specialization. If a partially-ordered V is defined before ordered or partially-ordered W in every translation unit, the initialization of V is sequenced before the initialization of W (or happens-before, if the program starts a thread).

(since C++17)

3) Ordered dynamic initialization, which applies to all other non-local variables: within a single translation unit, initialization of these variables is always sequenced in exact order their definitions appear in the source code. Initialization of static variables in different translation units is indeterminately sequenced. Initialization of thread-local variables in different translation units is unsequenced.

If the initialization of a non-local variable with static or thread storage duration exits via an exception, std::terminate is called.

[edit] Early dynamic initialization

The compilers are allowed to initialize dynamically-initialized variables as part of static initialization (essentially, at compile time), if the following conditions are both true:

1) the dynamic version of the initialization does not change the value of any other object of namespace scope prior to its initialization

2) the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.

Because of the rule above, if initialization of some object o1 refers to a namespace-scope object o2, which potentially requires dynamic initialization, but is defined later in the same translation unit, it is unspecified whether the value of o2 used will be the value of the fully initialized o2 (because the compiler promoted initialization of o2 to compile time) or will be the value of o2 merely zero-initialized.

inline double fd() { return 1.0; }extern double d1;double d2 = d1; // unspecified: // dynamically initialized to 0.0 if d1 is dynamically initialized, or // dynamically initialized to 1.0 if d1 is statically initialized, or // statically initialized to 0.0 (because that would be its value // if both variables were dynamically initialized)double d1 = fd(); // may be initialized statically or dynamically to 1.0

[edit] Deferred dynamic initialization

It is implementation-defined whether dynamic initialization happens-before the first statement of the main function (for statics) or the initial function of the thread (for thread-locals), or deferred to happen after.

If the initialization of a non-inline variable(since C++17) is deferred to happen after the first statement of main/thread function, it happens before the first ODR-use of any variable with static/thread storage duration defined in the same translation unit as the variable to be initialized. If no variable or function is ODR-used from a given translation unit, the non-local variables defined in that translation unit may never be initialized (this models the behavior of an on-demand dynamic library). However, as long as anything from a translation unit is ODR-used, all non-local variables whose initialization or destruction has side effects will be initialized even if they are not used in the program.

If the initialization of an inline variable is deferred, it happens before the first ODR-use of that specific variable.

(since C++17)
// ============// == File 1 ==#include "a.h"#include "b.h"B b;A::A() { b.Use(); }// ============// == File 2 ==#include "a.h"A a;// ============// == File 3 ==#include "a.h"#include "b.h"extern A a;extern B b;int main(){ a.Use(); b.Use();}// If a is initialized before main is entered, b may still be uninitialized// at the point where A::A() uses it (because dynamic initialization is// indeterminately sequenced across translation units)// If a is initialized at some point after the first statement of main (which odr-uses// a function defined in File 1, forcing its dynamic initialization to run),// then b will be initialized prior to its use in A::A

[edit] Static local variables

For initialization of locals (that is, block scope) static and thread-local variables, see static local variables.

Initializer is not allowed in a block-scope declaration of a variable with external or internal linkage. Such a declaration must appear with extern and cannot be a definition.

[edit] Class members

Non-static data members can be initialized with member initializer list or with a default member initializer.

[edit] Notes

The order of destruction of non-local variables is described in std::exit.

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DRApplied toBehavior as publishedCorrect behavior
CWG 270C++98the order of initializing static data members
of class templates was unspecified
specified as unordered except for
explicit specializations and definitions
CWG 441C++98non-local references with static storage duration were
not always initialized before dynamic initializations
considered as static initialization, always
initialized before dynamic initializations
CWG 1415C++98a block-scope extern variable
declaration could be a definition
prohibited (no initializer
allowed in such declarations)
CWG 2599C++98it was unclear whether evaluating function
arguments in the initializer is part of initialization
it is part of initialization

[edit] See also

C documentation for Initialization

Initialization - cppreference.com (2024)

FAQs

How do you initialize a reference in CPP? ›

Initialization of references (C++ only)
  1. When it is used in a parameter declaration.
  2. In the declaration of a return type for a function call.
  3. In the declaration of class member within its class declaration.
  4. When the extern specifier is explicitly used.

How do you initialize CPP? ›

You can initialize variables in these contexts:
  1. In the definition of a variable: C++ Copy. int i = 3; Point p1{ 1, 2 };
  2. As one of the parameters of a function: C++ Copy. set_point(Point{ 5, 6 });
  3. As the return value of a function: C++ Copy.
Apr 3, 2023

How do you initialize a list in CPP? ›

The syntax begins with a colon(:) and then each variable along with its value separated by a comma. The initializer list does not end in a semicolon. Syntax: Constructorname(datatype value1, datatype value2):datamember(value1),datamember(value2) { ... }

How do you initialize a structure in CPP? ›

To initialize struct in C++, this is the code:
  1. #include <iostream>
  2. // Struct using aggregate initialization.
  3. struct Point {
  4. int x;
  5. int y;
  6. };
  7. // Struct using constructor initialization.
  8. struct Rectangle {
Nov 3, 2023

How do you initialize references? ›

References are initialized in the following situations:
  1. 1) When a named lvalue reference variable is declared with an initializer.
  2. 2) When a named rvalue reference variable is declared with an initializer.
  3. 3) In a function call expression, when the function parameter has reference type.

Can we initialize reference variable? ›

There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.

What is initialization in C++ with example? ›

Initialization of a variable provides its initial value at the time of construction. The initial value may be provided in the initializer section of a declarator or a new expression. It also takes place during function calls: function parameters and the function return values are also initialized.

What is an example of initialization? ›

Initialization occurs when you assign an initial value to a variable. Here's an example: const color = "green"; In the snippet above, we initialized the color variable with an initial value of "green" .

What is default initialization in C++? ›

default-initialization – If T is a class, the default constructor is called; if it's an array, each element is default-initialized; otherwise, no initialization is done, resulting in indeterminate values. [ cppref1 ]

Why use initialization list C++? ›

Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

How to initialize memory in CPP? ›

Initialize memory: We can also initialize the memory using new operator: pointer-variable = new data-type(value); Example: int *p = new int(25); float *q = new float(75.25); Allocate block of memory: new operator is also used to allocate a block(an array) of memory of type data-type.

How do you initialize a class variable in CPP? ›

The simplest things to initialize are native types. int s, char s, pointers, and so on are easy to deal with. Consider a simple class and its default constructor: class Foo { public: Foo() : counter_(0), str_(NULL) {} Foo(int c, string* p) : counter_(c), str_(p) {} private: int counter_; string* str_; };

How to initialize string in cpp? ›

The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." strcpy(s1, s2); Copies string s2 into string s1.

How to initialize a bool in CPP? ›

In C++ the boolean type is called bool. Boolean variables work just like the other types: bool fred; fred = true; bool testResult = false; The first line is a simple variable declaration; the second line is an assignment, and the third line is a combination of a declaration and as assignment, called an initialization.

How to initialize float in cpp? ›

Declaring a float in c++ is as simple as saying: float variable_name; float here is the data type and as you can guess the variable name could be anything that well explains the purpose of its use.

How do references work in CPP? ›

C++ added the so-called reference variables (or references in short). A reference is an alias, or an alternate name to an existing variable. For example, suppose you make peter a reference (alias) to paul , you can refer to the person as either peter or paul .

How do you pass a reference string in CPP? ›

In C++, you can pass a string by reference using the ' &' symbol in the function parameter list. This allows you to modify the original string directly within the function.

Can you reassign a reference C++? ›

Once defined, a reference cannot be reassigned because it is an alias to its target. What happens when you try to reassign a reference turns out to be the assignment of a new value to the target. Because arguments of a function are passed by value, a function call does not modify the actual values of the arguments.

Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 5897

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.