Scope, Duration and Linkage Flashcards
What is meant by a variable’s scope?
Scope determines where a variable is accessible.
Explain duration of a variable
Duration determines when a variable is created and destroyed
What is the linkage of a variable?
Linkage determines whether the variable can be exported to another file or not
What is the scope of global variables?
Global scope (a.k.a. file scope), which means they can be accessed from the point of declaration to the end of the file which they are declared
What is the duration of a global variable?
They have static duration, which means they are created when the program is started, and destroyed when it ends
What is the linkage of a global variable?
They can have either internal or external linkage, via the static and external keywords respectively
How should you define a global constant in C++17
pragma once
Define them as inline constexpr global variables in a header file
Constants.h
constexpr int MAX_VALUE = 100;
What is static duration?
When a variable is created when the program starts and destroyed when it ends
What is internal linkage?
When an identifier can only be used in the file in which it is defined
What is automatic duration?
When a local variable is created at point of definition and destroyed when the block is exited
What is automatic duration?
When a local variable is created at point of definition and destroyed when the block is exited
What effect does using keyword static have on a global variable?
It gives it internal linkage; meaning the variable cannot be exported to other files
What effect does using keyword static have on a local variable?
It gives it static duration, meaning the variable will only be created once, and will not be destroyed until the end of the program
Variable with block/local scope can only be accessed from point of declaration until the end of the block. Three examples are:
Local variables, function parameters and program defined type definitions (such as enums and classes) declared inside a block
Variables and functions with global scope can be accessed from the point of declaration to the end of the file. This includes (3)
Global variables
functions
program defined type definitions (such as enums or classes) declared inside a namespace or in the global scope
Define automatic duration and give two examples
Variables which are created at the point of definition, and destroyed when the block they are part of ends.
E.g. local variables and function parameters
Define static duration and give two examples of variables with static duration
Variables which are created when the program begins and destroyed when it ends.
E.g.
global variables
static local variables