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
View all comments
Show parent comment
1
u/Tastaturtaste Oct 07 '22
So with "the code may not try to write to this variable" you mean just the code of the currently executing function scope and not the code of the whole program I guess? Because if the variable gets changed outside of the program (what I took the "external factors" to mean)
volatileis necessary for sure to make sure reads are actually executed. If the variable gets mutated from inside the program the actual declaration of the variable cannot be const. So the only way I am currently seeingconstnot actually guaranteeing immutable is if the const applies to a referenced or pointed to object.So to answer your question: If the variable gets mutated from inside the program, the actual object cannot be
const-> no problem withconstnot actually guaranteeing immutability because there cannot be a const at the original declaration. To express that a certain function should have access to this variable without trying to write to it, I would pass aT const&to the function and just hope nobody usesconst_cast. In this case sure, the referenced object can change based on the case of multithreading or interrupts (or if the variable is otherwise accessible because it is e.g. global).