You can observe the difference here: https://godbolt.org/
Lets say you have this code (yours does not compile: missing ;
and Point
has no []
):
struct Point
{
inline float x() const { return v[0]; }
inline float y() const { return v[1]; }
inline float z() const { return v[2]; }
float v[3];
};
int main() {
Point myPoint;
myPoint.v[0] = 5;
float myVal = myPoint.x() + 5;
return myVal;
}
Then gcc 9.2 emits:
Point::x() const:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
movss xmm0, DWORD PTR [rax]
pop rbp
ret
main:
push rbp
mov rbp, rsp
sub rsp, 16
movss xmm0, DWORD PTR .LC0[rip]
movss DWORD PTR [rbp-16], xmm0
lea rax, [rbp-16]
mov rdi, rax
call Point::x() const
movss xmm1, DWORD PTR .LC0[rip]
addss xmm0, xmm1
movss DWORD PTR [rbp-4], xmm0
movss xmm0, DWORD PTR [rbp-4]
cvttss2si eax, xmm0
leave
ret
.LC0:
.long 1084227584
I am not that proficient in reading assembler, but I thing comparing the above to the output with -O3
is convincing enough:
main:
mov eax, 10
ret
The generated code can vary dramatically depending on the context, I just wanted to know if there was any fundamental reasons it could never or would always happen.
The above example already disproves the "never". "Always", however is hard to get. The guarantee you get is that the resulting code behaves as if the compiler translated your code without optimizations applied. With few exceptions optimizations are usually not guaranteed. To be really sure I would only rely on looking at the compilers output in the realistic scenario.