How do you initialize a variable within a value region with an identical named variable in the content region without using a temporary or global variable?
If you want technical information on the wording, this is pretty easy. "Temporary" has a definite meaning in C ++ (see Β§12.2); any named variable you create is not temporary. Thus, you can simply create a local variable (which is not temporary) initialized with the correct value:
int a = 1234; { int b = a; int a = b; }
An even more reasonable possibility would be to use a variable reference in the outer scope:
int a = 1234; { int &ref_a = a; int a = ref_a; }
This does not create an additional variable at all - it simply creates an alias for the variable in the outer scope. Since the alias has a different name, we retain access to the variable in the external area without defining a variable (temporary or otherwise) for this. Many links are implemented as pointers inside, but in this case (at least using a modern compiler and optimization), I expect that this is not the case, that the alias will really be considered as another name related to the variable (and a quick test with VC ++ shows that it works this way - the generated assembler language does not use ref_a at all).
Another possibility on the same lines would look like this:
const int a = 10; { enum { a_val = a }; int a = a_val; }
This is somewhat similar to a link, except that in this case there is no room for an argument about whether a_val can be called a variable - it is absolutely not a variable. The problem is that an enumeration can only be initialized with a constant expression, so we must define the external variable as const for it to work.
I doubt that any of them is what the interviewer really did, but they all answer the question as indicated. The first (admittedly) purely technical information on definitions of terms. The second may be open to any argument (many think of references as variables). Although it limits the scope, there is no room for a question or argument for a third.
Jerry Coffin
source share