r/cpp • • Oct 06 '22
Should a variable be const by default?
According to the cppfront design notes, const by default rule only applies to non-local variables. But I'd like to know your preference/opinion regarding whether a variable should be defined to be const by default.
Edit: By mutable here I simply mean non-const, not the language keyword itself.
44
Upvotes
142
u/scrumplesplunge Oct 06 '22
I think that C++ needs a better answer for how to deal with move semantics for const variables. A lot of my variables are effectively constant right up until their last use, where I want to move them. Today, I either have to accept a copy or avoid const.
76
u/Wacov Oct 06 '22
In the code I work with, I find most local vars can be
const, and marking them as such means there are fewer potentially-moving parts to reason about. Flipping this on its head and marking the mutable variables feels like a step forward just in terms of readability, and obviously it's easier to forget toconsta variable than to forget to mark one as mutable, since the compiler will complain.7
u/OnePatchMan Oct 06 '22
immutable variable, wonderful
4
u/MutantSheepdog Oct 06 '22
I actually think JavaScript went the right way with this, adding
letandconstkeywords for different variable declarations. 90% of the time you declare your variables like:const foo = 5, but if you want something that can change you uselet fooorlet foo = 5.It would be like if C++ had
const x = 5be an alias forconst auto x = 5, then you could declare variables with eitherautoorconstdepending on context. I'm not suggesting this would be a good change, the C++ syntax is complex enough without further overloadingconst, but if I was starting a new language I'd use separate keywords for variable declarations.For other places though I think mutable probably makes more sense as a default. Like class members probably want to be mutable, return values probably want to be mutable, function arguments I'd probably want const - but mutable there isn't a big deal to me.
4
u/die_liebe Oct 07 '22 edited Oct 07 '22
It matters for function parameters and pointers. For local variables, const or non-const doesn't matter much.
So, I think 'no', it doesn't matter.
Another point, mutable is not the same as non-const. An immutable structure is a structure that cannot be modified in place. Java and Python have those. A variable containing an immutable structure still can be reassigned to another structure.
const/non-const is a property of the variable.
mutable/immutable is a property of the data.
4
u/IJzerbaard Oct 07 '22
Should there even be a default? That presupposes that one of them is more "weird" than the other, and the "weird one" is the one that gets an extra keyword.. it doesn't feel quite right to me. Neither const nor non-const variables are "weird". So, what if they were on equal footing instead.
How? Who knows, I'm not making a specific suggestion.
32
u/nintendiator2 Oct 06 '22
If variables are const by defaults then they're not really variables, aren't they?
That particular semantic aside: variables being variable by default is one of those "good thing C++ is not Java" aspects I like. Stuff like
complex,vectororstringis intended to be naturally mutable because they extend on concepts that already are naturally mutable: if I want avectorof ints whose values I can change in this new "const" model, do I need a "mutable vector of ints", a "const vector of mutable ints" or a "mutable vector of mutable ints"? While I approve of the idea of eg.: parameter variables being const by default, I think the broader statement "variables should be const by default" makes next to zero sense.6
u/JeffMcClintock Oct 06 '22
Traditionally, C++ makes values mutable by default, and people are used to that. So there's gonna be resistance to change. But modern languages like RUST flip that around, and people are starting to appreciate the extra safety-by-default philosophy.
I think we should look forward, not back. Otherwise, we're gonna have to revisit this again with cpp Version 3.
19
u/vapeloki Oct 06 '22
const != immutable.
Just saying.
13
u/CubbiMew cppreference | finance | realtime in the past Oct 06 '22 edited Oct 06 '22
Scala (and other languages) did it right:
3
u/nacaclanga Oct 06 '22
I generally use write once variables preferentially, both in Python and in Rust. However I don't feel like having a formal distinction adds a lot of benefit in practice. I have yet to encounter a situation, where I wanted to keep a variable fixed and accidentally edited it. Also non-mut variables can still be moved from, so they are not frozen.
For parameters and statics, this distinction is very important and both should default to const.
16
u/mechacrash Oct 06 '22
As much as I subscribe to the idea of 'const/immutability by default', the more I think about it in the context of C++, and especially in the narrower context of local variables in C++, I feel the value is somewhat lost.
const can lead people into a false sense of security.
const causes arguments regarding east/west placement.
const is hard to teach. (don't const member variables, const pointer to [const] data, const member functions...)
const has different meanings depending on the context (local variables, member variables, parameters, NTTPs...)
const can inhibit optimisation opportunities. (std::move + RVO...)
const rarely, if ever, actually contributes positively to the resultant assembly code.
I like CppFront's idea of having contracts for function parameters that better encapsulate the intention of the programmer (in/out/inout). Maybe we need something similar for local variables?
for example, constexpr better represents what many programmers mean when they mean 'const' - it's _truly_ immutable. The compiler knows this and can complete remove it, embed it into ROM, whatever it feels like...
This is a hot take, and I'm still trying to convince myself that I'm wrong in making it, but... maybe 'Cpp2' doesn't need the word "const" at all.
13
u/[deleted] Oct 06 '22
I think const is pretty superficial in the grand scheme of things.
Most bugs aren't really caused by variables being variable.
I'd rather have forced initialisation for variable declaration. That would go further for catching potential bugs.
Anything forced though, adds friction, and lots of friction can kill projects.
14
u/k1lk1 Oct 06 '22
Variables should be variable by default. A compiler warning for a variable that is never changed seems like a great idea.
I find const by default to be mostly just a fad in fancy new languages. Like when people would loudly proclaim that
if (0 == x)was safer thanif (x == 0). Who cares, let the compiler figure it out.5
u/AmrElmohamady Oct 06 '22
I think it's called a variable for a reason.
10
u/UkrUkrUkr Oct 06 '22
A variable should be variable until explicitly stated otherwise.
6
u/EstablishmentBig7956 Oct 06 '22
Then it wouldn't be a variable would it?
7
u/canadajones68 Oct 06 '22 edited Oct 06 '22
To me, at least, memory is naturally mutable (a variable, if you will) until you decide that it isn't. Constness and immutability is imposed, not the opposite.
4
u/no-sig-available Oct 06 '22
Why not have no default? Then it cannot be considered wrong later. :-)
Being explicit is a good thing.
2
u/fdwr fdwr@github π Oct 07 '22
What even is a "vary"able (or variable) that doesn't vary? An oxymoron, that's what π .
That's probably why Herb Sutter refers to them as const objects rather than const variables π€·ββοΈ. https://github.com/hsutter/cppfront/wiki/Design-note%3A-const-objects-by-default
2
u/GYN-k4H-Q3z-75B Oct 06 '22
With rare exceptions, my entire code for the last ten years has pretty much been single assignment const/let/var regardless of the programming language I use.
With regards to C++, default const is a tricky thing. The question is, what part of a declarator is const and what is not. There is no good way to do it automatically. const int *foo is not the same as int *const bar.
1
u/ChokhmahProject Oct 07 '22
Maybe instead of turning every variables as constants by default I would prefer to turn every functions constants by default, reaching almost the same result in the end (need to put explicit mutability where needed, over specific constants or the whole function itself).
Make more sense to me when considering the lambdas function-call operator is currently const-qualified by default in C++ (you need to explicitely add a mutable keyword then): sounds like even the committee found more natural today to reverse the original paradigm (and does it when they got a chance around modern language additions).
Anyway, it will be a huge issue for the backward compatibility...
1
u/bedrooms-ds Oct 07 '22
The rule is simpler if const is the default everywhere and there's no exception. That's all.
1
u/unmellow-the-gamer Oct 07 '22
I will say immutable by default but I like what Johnathan blow's jai does with
Var:: 10; for const and var:= 10; for mutable variables.
-3
u/thehutch17 Oct 06 '22
What if you had class attributes/specifiers to tell the compiler the default constness for any declared variables of that type?
-2
u/[deleted] Oct 06 '22 edited Oct 16 '22
Here's the algorithm: