Search

6.3 — Local variables

In lesson 2.4 -- Introduction to local scope, we introduced local variables, which are variables that are defined inside a function (including function parameters).

It turns out that C++ actually doesn’t have a single attribute that defines a variable as being a local variable. Instead, local variables have several different properties that help differentiate how local variables behave from other kinds of (non-local) variables. We’ll explore these properties in this and upcoming lessons, as well as a few other local variable related topics of note.

Local variables have block scope

An identifier’s scope determines where an identifier can be accessed within the source code. Scope is a compile-time property.

Local variables have block scope, which means they are in scope from their point of definition to the end of the block they are defined within.

Although function parameters are not defined inside the function body, for typical functions they can be considered to be part of the scope of the function body block.

The exception case is for function-level exception handling (which we cover in lesson 14.7 -- Function try blocks).

All variable names within a scope must be unique

Variable names must be unique within a given scope, otherwise any reference to the name will be ambiguous. Consider the following program:

The above program doesn’t compile because the variable x defined inside the function body and the function parameter x have the same name and both are in the same block scope.

Local variables have automatic storage duration

A variable’s storage duration (usually just called duration) determines what rules govern when and how a variable will be created and destroyed. In most cases, a variable’s storage duration directly determines its lifetime.

For example, local variables have automatic storage duration, which means they are created at the point of definition and destroyed at the end of the block they are defined in. For example:

For this reason, local variables are sometimes called automatic variables.

Local variables in nested blocks

Local variables can be defined inside nested blocks. This works identically to local variables in function body blocks:

In the above example, variable y is defined inside a nested block. Its scope is limited from its point of definition to the end of the nested block, and its lifetime is the same. Because the scope of variable y is limited to the inner block in which it is defined, it’s not accessible anywhere in the outer block.

Note that nested blocks are considered part of the scope of the outer block in which they are defined. Consequently, variables defined in the outer block can be seen inside a nested block:

Local variables have no linkage

Identifiers have another property named linkage. An identifier’s linkage determines whether other declarations of that name refer to the same object or not.

Local variables have no linkage, which means that each declaration refers to a unique object. For example:

Scope and linkage may seem somewhat similar. However, scope defines where a single declaration can be seen and used. Linkage defines whether multiple declarations refer to the same object or not.

Linkage isn’t very interesting in the context of local variables, but we’ll talk about it more in the next few lessons.

Variables should be defined in the most limited scope

If a variable is only used within a nested block, it should be defined inside that nested block:

By limiting the scope of a variable, you reduce the complexity of the program because the number of active variables is reduced. Further, it makes it easier to see where variables are used (or aren’t used). A variable defined inside a block can only be used within that block (or nested blocks). This can make the program easier to understand.

If a variable is needed in an outer block, it needs to be declared in the outer block:

The above example shows one of the rare cases where you may need to declare a variable well before its first use.

New developers sometimes wonder whether it’s worth creating a nested block just to intentionally limit a variable’s scope (and force it to go out of scope / be destroyed early). Doing so makes that variable simpler, but the overall function becomes longer and more complex as a result. The tradeoff generally isn’t worth it. If creating a nested block seems useful to intentionally limit the scope of a chunk of code, that code might be better to put in a separate function instead.

Best practice

Define variables in the most limited existing scope. Avoid creating new blocks whose only purpose is to limit the scope of variables.

Quiz time

Question #1

Write a program that asks the user to enter two integers, one named smaller, the other named larger. If the user enters a smaller value for the second integer, use a block and a temporary variable to swap the smaller and larger values. Then print the values of the smaller and larger variables. Add comments to your code indicating where each variable dies. Note: When you print the values, smaller should hold the smaller input and larger the larger input, no matter which order they were entered in.

The program output should match the following:

Enter an integer: 4
Enter a larger integer: 2
Swapping the values
The smaller value is 2
The larger value is 4

Show Solution

Question #2

What’s the difference between a variable’s scope, duration, and lifetime? By default, what kind of scope and duration do local variables have (and what do those mean)?

Show Solution


6.4 -- Introduction to global variables
Index
6.2 -- User-defined namespaces

210 comments to 6.3 — Local variables

  • Nahin

    Do those 'multiple declarations' in the sentence below refer to the forward declarations of a non-static function in as many files as we want?

    > Linkage defines whether multiple declarations refer to the same object or not.

  • AE35_Unit

    Thanks Nascar, I went back and looked at all your recommendations, they really helped. I can't thank you enough. My code looks better and proper now.  AS far as where I am with studying, I've just been going straight through this lesson plan from the beginning.  I've seen tutorial videos on the youtube and would based on the one C++ class I had at university I would say I'm about one and 1/3 semesters.  I just enough about classes to creates small and easy ones so I'm looking forward to your sections on the subject. Also I used pointers and references pointers in the above, I try to use them if I'm able so as to get a more solid understanding of them as well. I see that the pointers section are in the near future.  Right now I'm at 6.9 Why global variables are evil, and after I finish all of 6 I'll probably go back for a bit of review.  Again, thanks for all your help. Cheers.

  • AE35_Unit

    Again trying to utilize concepts learned from previous chapters.  This could be written a lot faster and easier to read but I find that by using previous lessons I get a better grasp on the course's teaching's.

    ae35unit.cpp

    main.cpp

    • nascardriver

      If you let me know how much of C++ already know by stating a chapter number (eg. "I know C++ up to, and including, chapter P") I can give you better suggestions.

      Still going with your lander huh? That's nice, keeps the fun up :)

      - Missing #include <cstdint>
      - `int_fast16_t` should be `std::int_fast16_t`
      - By using pointers, you're allowing the caller to pass in a `nullptr`. This can be avoided by using `gsl::not_null` from the guidelines support library or by using references.
      - If you can, initialize variables (`temp`).
      - main.cpp:16: `ae` is not an object, it has no lifetime, only a scope. We talk about the scope later in this chapter.
      - main.cpp:23: There's no need for a global namespace selector here.

      If you weren't programming a lander, here are some extra notes that I don't want to let go unnoticed:
      - Don't restrict integers unless you have a reason to (Your reason is speed). Plain `int` is fine most of the time.
      - Don't use `std::endl` unless you have a reason to (Your reason is that logs are critical).

Leave a Comment

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