Why is it okay to declare a STRUCT inside a nested loop?

Efficiency at this level is the compiler's concern in most cases. The compiler may well reuse the same stack space for each RGBTRIPLE! (Although it doesn't have to.)

Putting the RGBTRIPLE within the smallest brace pair (scope) that needs it prevents you from accidentally, erroneously accessing that variable outside that scope, when the variable's contents may not be valid.


Still, are thousands of iterations of the same declaration is better than a single declaration right before the first loop?

Sure this is all right. Either way, a good compiler will not emit code having any performance difference.

What might make for a modest linear performance change would be to call fread() less often.

for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++) {
    RGBTRIPLE triple[bi.biWidth];
    fread(triple, sizeof triple, 1, inptr);
    fwrite(triple, sizeof triple, 1, outptr);
}

or even

RGBTRIPLE triple[biHeight][bi.biWidth];
fread(triple, sizeof triple, 1, inptr);
fwrite(triple, sizeof triple, 1, outptr);

Lots of factors go into coding consideration. Avoid focusing on micro optimizations such as these.


What's important to understand here is that the statement RGBTRIPLE triple; declares the variable but does not directly correspond to "creating storage," or indeed translate to any machine language output at all.

You're just making a statement to the compiler about scope and usage of this variable (and declaring inside the most local block is a good-practice way of saying you only want it to be valid within that area). You could have put this line outside the loops, or at the top of its function, with no change to the executable output.

The compiler's job is to effectively create space on the stack for runtime use of local variables. In practice, it will simply reuse that same space used over and over again for each loop iteration. (People here will tell you, correctly, that this is not guaranteed, behavior which is technically true, but in practice it will always reuse the same space, as if you'd declared it above the loops.)

Tags:

C

Cs50