Reputation: 108
If I have code like this:
{
int x = f();
if (g(x)) return;
int y = h();
// use y
}
Will the compiler probably realize that x is not used after the if
statement and that it can put the variable y
in the register that x
occupied? I know that all compilers are different, but the question is whether this is a common optimization that I can reasonably rely on. I am wondering because I want to let the optimizer elide the extra registers rather than having to come up with names like this_variable_holds_x_then_y
.
Would it help to add an extra scope around x
so that the compiler can see it's inaccessible from outside it?
Upvotes: 2
Views: 103
Reputation: 106096
Yes - it's a very simple optimisation that any modern compiler would do. You can also check easily for yourself - most compilers support a "-S" or other command-line option that produces assembly language output (or you can disassemble the machine code).
Upvotes: 2