Variables and assignment
How a program names values and changes what the names hold. CS2023 SDF-Fundamentals starts here, and five core concepts of the group need a home.
Concepts
- Assignment
Assignment gives a variable a new value: the program computes the expression on the right and stores the result in the place on the left. In some languages an assignment is also an expression.
intro - Constant
A constant is a name for a value that does not change while the program runs. A compile-time constant has a value that the compiler knows, and a run-time constant gets its value once and keeps it.
intro - Initialization
Initialization gives a variable its first value. Some languages give a default value such as zero, others reject a read before it, and in C and C++ such a read can give a garbage value.
intro - Variable
A variable is a name for a value that can change while the program runs. In some languages the name stands for a storage place that holds the value, and in others it refers to an object.
intro - Default value
A default value is the value that a variable, a field or a parameter gets when the program gives none, such as 0, false or null. Some languages give one to each variable, and others only to fields.
core - Destructuring assignment
Destructuring assignment binds several names from the parts of one composite value, such as a tuple, an array or an object. The pattern on the left can skip parts, collect the rest and nest.
core - Uninitialized variables
An uninitialized variable has no value that the program set before a read. In C and C++ the read gives an unpredictable value, and Java, C# and Rust reject the read at compile time.
core - Variable lifetime
The lifetime of a variable is the time that it exists while the program runs. A local variable lives for one call or block, a global one for the whole run, and a closure can make a local live longer.
core - Single assignment
With single assignment, a variable gets a value once and keeps it. Erlang allows only single assignment, other languages offer it with const, final or let, and compilers use it in SSA form.
advanced
Tasks
- Declare a constant
Give a fixed value a name that the program cannot assign again, with const, final, constexpr or readonly. Know which constants the compiler computes, and why a constant object can still change inside.
10 languagesintro - Declare a variable
Declare a variable, give it a first value and assign it new values, with a named or an inferred type. Know which languages need a declaration and which make a variable on the first assignment.
10 languagesintro - Swap two values
Exchange the values of two variables or two items of a list: with a temporary variable, with a tuple assignment, or with std::swap or mem::swap. The XOR trick fails when both are the same place.
10 languagesintro