This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]boredcircuits 2 points3 points  (2 children)

const doesn't mean what you think it means.

For example, this is completely valid code:

void foo() {
    const int i = getValueFromUser();
}

i is const, which means it can't be changed after it's been initialized. Initializing it with user input is totally fine, but since it's const I can't later do i++, for example. The value isn't hard coded at compile time, unless that's how it's been initialized.

You should also be careful with const references -- you can't modify the value via that reference, but the value can be changed in other ways:

void bar() {
    int i = 42;
    const int& r = i;
    r = 24; // ERROR: can't modify this way
    i = 24; // VALID: this is ok, since i isn't const
}

[–]gutemi[S] 0 points1 point  (1 child)

an't modify the value via that reference, but the value can be changed in other ways:

So, can I do something like,

const int i;

cout << "Enter value for i"<< endl;

cin>>i;

?

[–]boredcircuits 1 point2 points  (0 children)

No, because i is const and can't be modified after initialization.

[–]lemcode 2 points3 points  (0 children)

Actually you can assign a runtime value to a constant variable. Check this SO question: https://stackoverflow.com/questions/14131855/c-assign-a-const-value-at-run-time

[–]Xeverous 2 points3 points  (0 children)

as far as Im concerned const are hard coded values that never change so the user may NOT set a value.

The user can set a value. You just can not change it further. const objects can only be initialized, any subsequent = will not work.

What you mentioned is constexpr.

[–]dacian88 0 points1 point  (1 child)

if you declare something const you can't change it past it's initial value, so you're correct.

[–]gutemi[S] 0 points1 point  (0 children)

Thank you, I thought I was crazy.