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

后端 未结 8 1438
广开言路
广开言路 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:37

    I don't actually suggest doing this, but you could use creative variable shadowing to simulate something like what you want:

    void SomeFunction(int a)
    {
        // Here some processing happens on a, for example:
        a *= 50;
        a %= 10;
        if(example())
           a = 0;
        {
            const int b = a;
            const int a = b;  // New a, shadows the outside one.
            // Do whatever you want inside these nested braces, "a" is now const.
        }
    }
    

提交回复
热议问题