A variable that is read-only after assignment at runtime?

A fairly new programmer here, and a preliminary apology for the stupid questions.

I have an int variable in a program that I use to determine how long my arrays should be in some of my structures. I used it in the header as const int . Now I want to fork my program to specify a variable with different values ​​depending on the arguments specified, but keep it read-only after I assign it at runtime.

A few ideas that I had to make. Is there a preferred way?

  • Declare const int * in my header and assign it a const int in my main function, but that seems awkward.
  • Make it a simple int in my main function.
  • Passing a variable as an argument when calling a function.
  • Something else I did not think.
+8
c ++ const constants
source share
4 answers

I would use a static variable function and a simple function. Note:

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

Since this is a static variable of the function level, it is initialized only for the first time. Thus, the initialValue parameter initialValue useless after the first start of the function. Therefore, all you have to do is make sure that the first function call is the one that initializes it.

+9
source share

C ++ has no built-in solution for this, but if you really want to make sure that your int is assigned only once, you can create your own special int class:

 class MyConstInt { public: MyConstInt(): assigned(false) {} MyConstInt& operator=(int v) { assert(!assigned); value = v; assigned = true; return *this; } operator int() const { assert(assigned); return value; } private: int value; bool assigned; }; MyConstInt mi; // int i = mi; // assertion failure; mi has no value yet mi = 42; // mi = 43; // assertion failure; mi already has a value int* array = new int[mi]; 
+6
source share

When do you know the correct value exactly? If you read it from a file or something else, you can simply say:

 const int n = determine_correct_value(); 
+1
source share

I am tempted to say that what you want does not make sense. A constant is something that does not change its value, and not something that can change its value once or twice. If you want a global variable, just make it volatile.

On the other hand, if you have values ​​with a constant constant, you simply declare and initialize them at the same time, following the general C ++ directive to declare as close as possible to the site of use. For example, note the use of constants in the following local area:

 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 not even generate any special code for variables at all, if their value is already known by other means.

0
source share

All Articles