这是一些提供的(CS50)代码的片段,这些代码在嵌套循环中一遍又一遍地声明相同的STRUCT“三元组”。为什么这样可以呢?在我看来,将STRUCT“三元组”声明为嵌套循环的范围上方并在每次迭代中更改值会更有效。
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
Run Code Online (Sandbox Code Playgroud)
。
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);
}
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,此级别的效率是编译器关心的问题。编译器可以为每个RGBTRIPLE重新使用相同的堆栈空间!(尽管不是必须的。)
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.