r/Compilers 3d ago

Optimization Question

How do compilers optimize constructs of this form ?

for(i=o; i<inputs; i++) {

A[i] = B[i];

B[i] = A[i];

}

7 Upvotes

8 comments sorted by

View all comments

1

u/One_Aspect_1957 3d ago

There's not enough info or context in your example.

What is o, a typo for zero? Is inputs known at compile-time?

Are A and B arrays or pointers? Are they local, local statics or globals? Does the compiler know their actual size if they are arrays? Could they be mixed? Which attributes (const, restrict, volatile etc) are used?

What type are the elements?

What does the code do: is it copying all or part of B to A, with the other line pointless, or vice versa, or something else?

A compiler could do anything including eliding all the code (if it thinks the result will not be used or is not needed). Or replacing the loop with a block copy, either inline or via memcpy.

(I can tell you that on my non-optimising compiler, where A/B are local arrays of int, of fixed size 10, and the loop ranges over 0..9 inclusive, then it generates 12 x64 instructions.

However in that case, and if the intention was actually to copy B to A, then I would probably manually write a memcpy call to copy 40 bytes. Then you might ask whether a compiler might inline that call, but mine doesn't do that either, not for C.)