Value initialization and zero initialization in C++

 Value initialization and zero initialization

When a variable is initialized with empty braces, value initialization takes place. In most cases, value initialization will initialize the variable to zero (or empty, if that’s more appropriate for a given type). In such cases where zeroing occurs, this is called zero initialization.

int width {}; // zero initialization to value 0

Q: When should I initialize with { 0 } vs {}?

Use an explicit initialization value if you’re actually using that value.

int x { 0 }; // explicit initialization to value 0
std::cout << x; // we're using that zero value

Use value initialization if the value is temporary and will be replaced.

int x {}; // value initialization
std::cin >> x; // we're immediately replacing that value

Initialize your variables

Initialize your variables upon creation. You may eventually find cases where you want to ignore this advice for a specific reason (e.g. a performance critical section of code that uses a lot of variables), and that’s okay, as long the choice is made deliberately.

For more discussion on this topic, Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) make this recommendation themselves here.

We explore what happens if you try to use a variable that doesn’t have a well-defined value in lesson 1.6 -- Uninitialized variables and undefined behavior.

Best practice

Initialize your variables upon creation.

Comments

Popular posts from this blog

Whiteboarding Interviews

Version Control with Git: A Beginner’s Guide

Callback function in JavaScript