Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

constants

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 arrays should be in some of my structures. I used to put it in my header as a const int. Now, I want to fork my program to give the variable different values depending on the arguments given in, but keep it read-only after I assign it at run-time.

A few ideas I've had to do this. Is there a preferred way?

  1. Declare a const int * in my header and assigning it to a const int in my main function, but that seems clunky.
  2. Make it a plain int in my main function.
  3. Pass the variable as an argument when the function is called.
  4. Something else I haven't thought of yet.
like image 755
Blue Magister Avatar asked Oct 24 '11 18:10

Blue Magister


People also ask

What is read only variable?

Read-only variables can be used to gather information about the current template, the user who is currently logged in, or other current settings. These variables are read-only and cannot be assigned a value.

What is variable in assignment?

Variable Assignment To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values.

What is a constant variable?

A constant variable, sometimes known as a control variable, is something you keep the same during an experiment.

Which of the following is a variable assignment?

Which of the following is a variable assignment statement? Explanation: To assign a value to variable, a variable assignment statement is used. The symbol used for variable assignment is ':=' whereas when we assign some value to a signal, <= statement is used.


1 Answers

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.

like image 196
Nicol Bolas Avatar answered Nov 15 '22 18:11

Nicol Bolas