Suppose that I wanted to read an integer from cin and then make it immutable. I can do:
int a;
cin >> a;
const int b = a;
Then, I would have a variable (b) which is initialized to user data, but cannot be changed. However, I think I'm abusing the const keyword here. Is this an acceptable thing to do? The compiler seems to be okay with it, but I'm just wondering if it's right from a stylistic point of view.
It's completely fine. You're free to create const variables from non-const data, even user-entered data.
You might even write a function so you don't have the stray a variable sitting around afterward. For example:
int read_int(std::istream& in) {
int a;
in >> a;
return a;
}
int const b = read_int(std::cin);
This is a philosophical question. :)
In my opinion you are not doing any stylistic aberration. You are defined a variable that from that point do not change anymore. The history of that variable value is negligible. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With