LyingOnTheSky LyingOnTheSky - 4 months ago 9
C++ Question

Make a variable unusable/unaccessible in scope halfway

Let's say I have this code:

for (int i = 0; i < x.size(); i++) {
auto &in = input[i];
auto &func = functions[i];
auto &out = output[i];
// pseudo-code from here:
unaccessiable(i);
i = func(in); // error, i is not declared
// useful when you mistake out for i
}


I need to achieve effect that a variable is not accessible or usable after a certain line in the code. (in this code, after the
unaccessiable(i)
)
Specifically I want to disable the iterator of a for's loop.

NOTE: This is only for code correctness, and nothing beyond that. So lambdas (non-compile-time solutions) are just performance hindering.

Answer

The simplest way to make a name unusable halfway through a block, is to declare it as struct:

for (int i = 0; i < x.size(); i++) {
    auto &in = input[i];
    auto &func = functions[i];
    auto &out = output[i];
    // pseudo-code from here:
    struct i;     // ←
    i = func(in); // error, i is a type
    // useful when you mistake out for i
}

Alternatively you can put the code after the "here" in a nested block where you can redeclare i as a variable of some ungood type, which might give better diagnostics.

Comments