Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

cs50

Here's a snippet of some supplied (CS50) code that declares the same STRUCT 'triple', over and over again inside of a nested loop. Why is this okay? In my mind, it would be more efficient to declare the STRUCT 'triple' just above the scope of the nested loops and change the values each iteration.

typedef struct
{
    BYTE rgbtBlue;
    BYTE rgbtGreen;
    BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

.

 for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
    // iterate over pixels in scanline
    for (int j = 0; j < bi.biWidth; j++)
    {
        // temporary storage
        RGBTRIPLE triple;

        // read RGB triple from infile
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

        // write RGB triple to outfile
        fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
    }
like image 930
William Stephan Avatar asked Sep 14 '19 19:09

William Stephan


Video Answer


2 Answers

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.

like image 144
cxw Avatar answered Sep 29 '22 07:09

cxw


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.

like image 36
chux - Reinstate Monica Avatar answered Sep 29 '22 08:09

chux - Reinstate Monica