0

For example, will gcc/g++(version 9.4, or 7.3) remove unused c and pc in the output file, because this piece of code access only C::i and C::j, but not C::c andC::pc.

#include <iostream> struct C { // i, j is used below int i; int j; // c, pc is not used char c; char *pc; C() : i(2) {} }; int main() { C c; c.j = 9; std::cout << c.j << c.i << sizeof(c) << std::endl; } 


The problem I am confused with is almost solved, inspired by the site.

Now I understand that the field is accessed as a pointer plus an offset, thus without an access, there will be no code representing as such a pointer plus an offset, in the final executable file.

9

1 Answer 1

1

Compilers will not optimize out unused struct fields. In theory they might be allowed (but not required) to do so, but in practice it never happens. One reason is that the compiler normally sees only one translation unit at a time, and can never be sure that the field is not accessed in other translation units.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.