Here is a quick scribble of an idea I've been toying with...
Introduction
We propose const statements. A const statement makes a variable const.
Minimal Example
int main() {
int x;
x = 3; // OK
std::cout << x; // OK
const x;
x = 3; // ERROR: x is const
std::cout << x; // OK
}
Motivation
It is a common pattern to modify a variable during the first part of a function scope (for example, building out some data structure off to the side) and then intend for it not to be modified for the remainder of the scope (say, looking up the now filled-out data structure). In such situations, usually programmers simply leave the variable non-const for that remainder, and take the risk of accidental modification - but if a convieniant way was provided to "freeze" a variable it may mitigate this risk.
One might argue that the first part of the function could be factored out into a separate function that returns the variable into a const variable - or, equivalently a new class type created where the modifying part is placed into the constructor.
In practice, often the first part of the function that modifies the variable may not be solely responsible for that side effect, and is folded with other work. There may be many variables and a complex algorithm in play. In many cases such a factoring would be awkward and unnatural. As stated previously, we contend that most do not do that, and instead just leave the variable non-const.
Specification
A const statement has the form:
const N1, N2, ..., Nn;
where each Ni names a variable. It may only appear at function scope.
Informally, the effect of a const statement is to change the type of each Ni to the const version of its current type for the remainder of the function scope.
Formally, perhaps something like:
using __T = decltype(N);
__T* __p = &N;
const __T& N = (*__p);
With the differences that: __T and __p are exposition only, N may shadow a previous N at the same scope. N may be a qualified or unqualified name.
Thoughts?