简体   繁体   中英

c++ how to initialize global const variables sequentially

I have a problem with initializing global const variables:

int a;
const int b = a * a;

int main(int argc, char **argv) {
    a = std::stoi(argv[1]);
    ...
}

I would like to pass values to a and b in the runtime. However, the above code does not work for b . What should I do then? Thanks!!!

You can't and it's a real issue when using globals, which is why most large system developers (should) opt out of using the feature.

My favorite approach:

int get_global_a(int initial_value=0) {
  static int a = initial_value;
  return a;
}

int get_global_b(int a_value=0) {
  static int b = a_value * a_value;
  return b;
}

/* Make sure this is the first line you execute in your program, but not before main! */
void initialize_all_globals(/* all necessary params */) {
    int a = std::stoi(argv[1]);
    get_global_a(a);
    get_global_b(get_global_a());
}

You can initialize it with a static int like this at runtime. Later changes to the variable lead to a compile error:

#include <iostream>

static int hidden_b;
const int& b(hidden_b);

int main(int argc,char** argv) {
    int a = std::stoi(argv[1]);
    hidden_b = a*a;
    std::cout << b << std::endl;
    //b = 3; // compile error

    // problems arise, if you change the hidden variable
    /*hidden_b = 3;
    std::cout << b << std::endl;*/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM