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

后端 未结 8 1388
广开言路
广开言路 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.
        }
    }
    
    0 讨论(0)
  • 2020-12-01 09:37

    Answers were pretty solid, but honestly I can't really think of a GOOD situation to use this in. However in the event you want to Pre-Calculate a constant which is basically what you are doing you have a few main ways You can do this.

    First we can do the following. So the compiler will simply set CompileA# for us in this case it's 50, 100, and 150.

    const int CompileA1 = EarlyCalc(1);
    const int CompileA2 = EarlyCalc(2);
    const int CompileA3 = EarlyCalc(3);
    
    int EarlyCalc(int a)
    {
        a *= 50;
        return a;
    }
    

    Now anything beyond that there's so many ways you can handle this. I liked the suggestion as someone else had mentioned of doing.

    void SomeFunc(int a)
    {
        const int A = EarlyCalc(a);
        //We Can't edit A.
    }
    

    But another way could be...

    SomeFunc(EarlcCalc(a));
    
    void SomeFunc(const int A)
    {
        //We can't edit A.
    }
    

    Or even..

    SomeFunction(int a)
    {
        a *= 50;
        ActualFunction(a);
    }
    
    void ActualFunction(const int A)
    {
        //We can't edit A.
    }
    
    0 讨论(0)
提交回复
热议问题