Is there a way to create a variable after declaring it?

Possible duplicate:
Is there any ninja trick to make a variable constant after it is declared?

Sometimes in C or C ++ we have a variable that can be const, but we need to take some lines of code to initialize it.

Is there any way to tell the compiler that from some point in the function some already built variable should be considered as const until its area ends?

Sort of:

int c = 0;
// the value of c is initialized here
switch(someVar) {
   case foo: c = 3; break;
   case bar: c = 4; break;
   default : c = 42; // what else?
}
// now c is constant
ASSUME_CONST_FROM_NOW(c) // some #pragma maybe?

I know that I can initialize a variable in a special function. This is actually not what I am asking.

Another example:

int c = 0; int d = 0;
{ /*some block of code that initializes both c and d jointly*/ }
ASSUME_CONST_FROM_NOW(c, d)

There is no function that can return two values โ€‹โ€‹at once without creating structures or classes.

, , .

+3
3

.

.

int getInitCValue(int const& someVar)
{
    // the value of c is initialized here
    switch(someVar)
    {
        case foo: return 3;
        case bar: return 4;
        default : return 42; // what else?
    }
}

int const c = getInitCValue(someVar);

: .

:

std::pair<int,int> const value = initalizePairOfValues(someValue);
int const& c = value.first;
int const& d = value.second;

2: Pรฉter Tรถrรถk (Peter, , ).

struct ConstValues
{
    ConstValues()
    {
         switch(....)
         // Initialize C/D
    }
    int const& getC() const {return c;}
    int const& getD() const {return d;}
    private:
       int c;
       int d;
};
+9

++ 0x - :

int const c = []() -> int { 
    int r; 
    switch(42) { 
    case 3: 
        r = 1; break; 
    case 4: 
        r = 2; break; 
    default: 
        r = 23; 
    }; 
    return r; 
}();
+8

{} , const, , , - . - :

#define CONSTIFY(T, NAME)                  \
for (bool p00 = true; p00; p00=false)      \
for (T p000 = NAME; p00; p00=false)        \
for (T const NAME = p000; p00; p00=false)

this should work in both C99 and C ++. Technically, this does not make your original variable const, but creates a new variable with the same contents for the dependent area.

And be careful that in some cases ( breakor continue) this can change the flow of control. But as long as you wrap it around something that is basically the whole body of a function, this should work.

+1
source

Source: https://habr.com/ru/post/1785395/


All Articles