Is there some ninja trick to make a variable constant after its declaration?

后端 未结 8 1391
广开言路
广开言路 2020-12-01 09:13

I know the answer is 99.99% no, but I figured it was worth a try, you never know.

void SomeFunction(int a)
{
    // Here some processing happens on a, for ex         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 09:25

    A pattern I used to use is to "hide" the argument with an _, so the code becomes

    void SomeFunction(int _a)
    {
        // Here some processing happens on a, for example:
        _a *= 50;
        _a %= 10;
        if(example())
           _a = 0;
    
        const int a = _a;
        // From this point on I want to make "a" const; I don't want to allow
        // any code past this comment to modify it in any way.
    }
    

    You could also use only const variables and make a function to compute the new value of a, if necessary. I tend more en more to not "reuse" variables en make as much as possible my variables immutable : if you change the value of something , then give it a new name.

    void SomeFunction(const int _a)
    {
        const int a = preprocess(_a);
        ....
    
    }
    

提交回复
热议问题