In what language? C's const is an unmodifiable runtime value for example, as is Zig's. Go is one language that I can think of where const is compile-time though.
In what language? C's const is an unmodifiable runtime value for example, as is Zig's. Go is one language that I can think of where const is compile-time though.
Bjarne's book calls these immutable variables "constants" which is completely crazy, but I guess indicates that the name is on purpose. This leads to the usual C++ insanity shortly afterwards in the book...
> An object that is a constant when accessed through one pointer may be variable when accessed in other ways.
Yeah, no. If the object were actually constant you can't do that, your language has betrayed the poor programmer. You can't "access" constants, you can use them to initialize variables, parameters, and so on, but they can't be "accessed" and that's where you've gone wrong here.
Rust's Quiz has a example showing what happens with actual constants, and it's not that
Different people will have different breaking points about when things have been stretched too far, meaning they are not willing to compromise on. Working with people who have not the same level of flexibility or rigidity or differ in different contexts can be a day-to-day pain.
I do agree that "immutable" would have been a better name, but I guess that angle hadn't been invented yet. :)
Immutable variables are a good idea (indeed I agree with Rust's choice to make variables immutable by default), but, they're not constants, and so this is an unnecessary confusion.
int x = 0;
int const *px = &x;
++x; // *px changed
There's no way to indicate true immutability in C++, unfortunately. The language does decree that any object (which in C++ parlance includes ints etc) with a const type cannot be mutated without triggering UB; but there's no way to declare a pointer or reference that can only point to such objects.