Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using c++ const on user-entered data?

Tags:

c++

constants

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.

like image 324
Ord Avatar asked Jun 02 '26 16:06

Ord


2 Answers

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);
like image 197
Rob Kennedy Avatar answered Jun 05 '26 05:06

Rob Kennedy


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. :)

like image 25
Davide Aversa Avatar answered Jun 05 '26 07:06

Davide Aversa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!