Search

1.4 — Variable assignment and initialization

In the previous lesson (1.3 -- Introduction to variables), we covered how to define a variable that we can use to store values. In this lesson, we’ll explore how to actually put values into variables and use those values.

As a reminder, here’s a short snippet that first allocates a single integer variable named x, then allocates two more integer variables named y and z:

Variable assignment

After a variable has been defined, you can give it a value (in a separate statement) using the = operator. This process is called copy assignment (or just assignment) for short.

Copy assignment is named such because it copies the value on the right-hand side of the = operator to the variable on the left-hand side of the operator. The = operator is called the assignment operator.

Here’s an example where we use assignment twice:

When we assign value 7 to variable width, the value 5 that was there previously is overwritten. Normal variables can only hold one value at a time.

Warning

One of the most common mistakes the new programmers make is to confuse the assignment operator (=) with the equality operator (==). Assignment (=) is used to assign a value to a variable. Equality (==) is used to test whether two operands are equal in value.

Copy and direct initialization

One downside of assignment is that it requires at least two statements: one to define the variable, and one to assign the value.

These two steps can be combined. When a variable is defined, you can also provide an initial value for the variable at the same time. This is called initialization.

C++ supports three basic ways to initialize a variable. First, we can do copy initialization by using an equals sign:

Much like copy assignment, this copies the value on the right-hand side of the equals to the variable being created on the left-hand side.

Second, we can do a direct initialization by using parenthesis.

For simple data types (like integers), copy and direct initialization are essentially the same. But for some advanced types, direct initialization can perform better than copy initialization. Prior to C++11, direct initialization was recommended over copy initialization in most cases because of the performance boost.

Uniform initialization in C++11

Unfortunately, direct initialization can’t be used for all types of initialization. In an attempt to provide a more consistent initialization mechanism, C++11 added a new syntax for direct initialization called brace initialization (also called uniform initialization) that uses curly braces:

Initializing a variable with empty braces indicates zero initialization. Zero initialization generally initializes the variable to zero (or empty, if that’s more appropriate for a given type).

Uniform initialization has the added benefit of disallowing “narrowing” conversions. This means that if you try to use uniform initialization to initialize a variable with a value it can not safely hold, the compiler will throw an warning or error. For example:

In the above snippet, we’re trying to assign a number that has a fractional component to an integer variable (that can not hold a fractional component). Copy and direct initialization would drop the fractional component, resulting in initialization of value 4 into variable width. However, with uniform initialization, this will cause the compiler to issue an error (which is generally a good thing, because losing data is rarely desired).

Best practice

Always 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.

Best practice

If you’re using a C++11 compatible compiler, favor uniform initialization.

Author's note

Many of the examples in this tutorial series were written before uniform initialization existed and thus still use copy or direct initialization. We’re working on getting these updated. Please forgive our lack of adherence to best practice in this regard.

Q: C++ provides copy, direct, and uniform initialization, and copy assignment. Is there a direct or uniform assignment?

No, C++ does not support a direct or uniform assignment syntax.

In C++11, move assignment was added, but it uses the same syntax as copy assignment. We cover move assignment in the chapter on smart pointers.

Initializing multiple variables

In the last section, we noted that it is possible to define multiple variables of the same type in a single statement by separating the names with a comma:

We also noted that best practice is to avoid this syntax altogether. However, since you may encounter other code that uses this style, it’s still useful to talk a little bit more about it, if for no other reason than to reinforce some of the reasons you should be avoiding it.

You can initialize multiple variables defined on the same line:

Unfortunately, there’s a common pitfall here that can occur when the programmer mistakenly tries to initialize both variables by using one initialization statement:

In the top statement, variable “a” will be left uninitialized, and the compiler may or may not complain. If it doesn’t, this is a great way to have your program intermittently crash and produce sporadic results. We’ll talk more about what happens if you use uninitialized variables shortly.

The best way to remember that this is wrong is to consider the case of direct initialization or uniform initialization:

This makes it seem a little more clear that the value 5 is only being used to initialize variable b or d, not a or c.

Quiz time

Question #1

What is the difference between initialization and assignment?

Show Solution

Question #2

What form of initialization should you be using (assume your compiler is C++11 compliant)

Show Solution


1.5 -- Introduction to iostream: cout, cin, and endl
Index
1.3 -- Introduction to variables

6 comments to 1.4 — Variable assignment and initialization

  • there is something i don't get; what is the use of an integer variable when it is in a program when we use curly braces. when i run the program i always found out that the value that i inserted in the curly braces doesn't seem to hold any value; please tell me the utility of the variable inside the curly braces

    thanks

  • Asgar

    Here is a quote (sorry, long quote) by Scott Meyers:
    "If you're an experienced C++ programmer and are anything like me, you initially approached C++11 thinking, "Yes, yes, I get it. It's C++, only more so." But as you learned more, you were surprised by the scope of the changes. auto declarations, range-based for loops, lambda expressions, and rvalue references change the face of C++, to say nothing of the new concurrency features. And then there are the idiomatic changes. 0 and typedefs are out, nullptr and alias declarations are in. Enums should now be scoped. Smart pointers are now preferable to built-in ones. Moving objects is normally better than copying them."

    He says 0 is out. What does he mean by that? We are discussing zero initialization in C++11 here and it seems 0's are still available.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]