C++ const keyword - use liberally?

前端 未结 12 2409
甜味超标
甜味超标 2020-12-04 18:12

In the following C++ functions:

void MyFunction(int age, House &purchased_house)
{
    ...
}


void MyFunction(const int age, House &purchased_house)         


        
12条回答
  •  温柔的废话
    2020-12-04 19:06

    You should use const on a parameter if (and only if) you would use it on any other local variable that won't be modified:

    const int age_last_year = age - YEAR;
    

    It's sometimes handy to mark local variables const where possible, since it means you can look at the declaration and know that's the value, without thinking about intermediate code. You can easily change it in future (and make sure you haven't broken the code in the function, and maybe change the name of the variable if it now represents something slightly different, which is changeable, as opposed to the previous non-changing thing).

    As against that, it does make the code more verbose, and in a short function it's almost always very obvious which variables change and which don't.

    So, either:

    void MyFunction(const int age, House &purchased_house)
    {
        const int age_last_year = age - YEAR;
    }
    

    or:

    void MyFunction(int age, House &purchased_house)
    {
        int age_last_year = age - YEAR;
    }
    

提交回复
热议问题