A variable that is read-only after assignment at run-time?

后端 未结 4 1032
小蘑菇
小蘑菇 2021-02-06 05:22

Fairly new programmer here, and an advance apology for silly questions.

I have an int variable in a program that I use to determine what the lengths of my a

4条回答
  •  甜味超标
    2021-02-06 06:11

    I'd use a function-static variable and a simple function. Observe:

    int GetConstValue(int initialValue = 0)
    {
      static int theValue = initialValue;
      return theValue;
    }
    

    Since this is a function-level static variable, it is initialized only the first time through. So the initialValue parameter is useless after the first run of the function. Therefore, all you need to do is ensure that the first call of the function is the one that initializes it.

提交回复
热议问题