Does GCC, or do compilers in general, remove variables which are operated on, yet do not at all affect the result of the code? For example, say main only contained
int a = 0;
int b = 0;
for (int i = 0; i < 10; i++) {
a += 10;
b += 10;
}
printf("%d", a);
Is the variable b ever present in memory or even operated on after compilation? Would there by any assembly logic storing and handling b? Just not positive whether this is something that's counted under deadcode elimination. Thanks.
Yes, absolutely. This is a very common optimization.
The best way to answer such questions for yourself is to learn a little bit of assembly language and read the code generated by the compiler. In this case, you can see that not only does GCC optimize b
entirely out of existence, but also a
, and it compiles the whole function into just the equivalent of printf("%d", 100);
.