Home > front end >  Is there a scenario where adding a const qualifier to a local variable could introduce a runtime err
Is there a scenario where adding a const qualifier to a local variable could introduce a runtime err

Time:03-05

Here's an (admittedly brain-dead) refactoring algorithm I've performed on several occasions:

  1. Start with a .cpp file that compiles cleanly and (AFAICT) works correctly.
  2. Read through the file, and wherever there is a local/stack-variable declared without the const keyword, prepend the const keyword to its declaration.
  3. Compile the .cpp file again
  4. If any fresh compile-time errors are reported, examine the relevant lines of code to determine why -- if it turns out the local-variable legitimately does need to be non-const, remove the const keyword from it; otherwise fix whatever underlying issue the const keyword's addition has revealed.
  5. Goto (3) until the .cpp file again compiles cleanly

Setting aside for the moment whether or not it's a good idea to "const all the local variables", is there any risk of this practice introducing a run-time/logic error into the program that wouldn't be caught at compile-time? AFAICT this seems "safe" in that it won't introduce regressions, only compile-time errors which I can then fix right away; but C is a many-splendored thing so perhaps there is some risk I haven't thought of.

CodePudding user response:

const has no runtime implications, that the compiler will not tell you at compile time and fail the build.

CodePudding user response:

If you're willing to accept a contrived example, you could enter the world of undefined behavior.

void increment(int & num)
{
      num;
}

int main()
{
    int n = 99;
    increment(const_cast<int&>(n));
    cout << n;
}

The above compiles and outputs 100. The below compiles and is allowed to do whatever it wants (but happened to output 99 for me). Modifying a const object through a non-const access path results in undefined behavior.

void increment(int & num)
{
      num;
}

int main()
{
    const int n = 99;
    increment(const_cast<int&>(n));
    cout << n;
}

Yes, this is contrived because why would someone do a const_cast on a non-const object? On the other hand, this is a simple example. Maybe in more complex code this might actually come up. Shrug I won't claim that this is a big risk, but it does fall under "any risk", as stated in the question.

  • Related