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

后端 未结 4 990
小蘑菇
小蘑菇 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:08

    I'm tempted to say that what you want doesn't make sense. A constant is something that doesn't change its value, not something that maybe changes its value once or twice. If you want a global variable, just make it non-constant.

    On the other hand, if you have scope-constant values, you would just declare and initialize them at the same time, following the general C++ guideline to declare as close to the usage site as possible. For example, mark the use of constants in the following local scope:

    for (auto it = v.begin(), end = v.end(); it != end; ++it)
    {
      const Foo & x = *it;
      const std::size_t n = x.get_number_of_bars();
    
      // use x and n ...
    
      const bool res = gobble(x, zip(n));
      if (res && shmargle(x)) { return 8; }
    }
    

    Here the compiler may even choose not to generate any special code for the variables at all if their value is already known through other means.

提交回复
热议问题