Pointer + reference technique
It does feel like a limitation of the C++ language that could be overcome with a new language feature.
The most efficient option I can see until then (in case you are doing more in the if else than just setting the reference, in which case you could use the ternary operator ?) is to use a pointer, and then set the reference to the pointer to avoid doing multiple dereferences when using the variable later on when every time you use the variable:
main.cpp
#include <iostream>
int main(int argc, char **argv) {
(void)argv;
int x = 1;
int y = 2;
int *ptr;
if (argc > 1) {
ptr = &x;
} else {
ptr = &y;
}
// One pointer dereference here, I don't see how to get rid of this.
int &z = *ptr;
// No pointer dereference on any of the below usages.
z = 3;
std::cout << x << std::endl;
std::cout << y << std::endl;
std::cout << z << std::endl;
}
Compile:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
run:
./main.out
output:
1
3
3
run again:
./main.out a
output:
3
2
3
If the if condition is known at compile time however, you could of course use the preprocessor or better, C++17 if constexpr: if / else at compile time in C++?
Related: Declare a reference and initialize later?