Tuesday 11 December 2018

c - Which is the better way to declare dummy variables for nested loops?





  1. The advantage of approach 1 is a slightly smaller file size due to less text characters in the source code:



    int i, j;
    for (i = 0; i < numRows; i++)
    for (j = 0; j < numCols; j++)
    //

  2. The advantage of approach 2 is the smaller scope of local variables.




    int i;
    for (i = 0; i < numRows; i++)
    {
    int j;
    for (j = 0; j < numCols; j++)
    //
    }




Even if the differences in optimizations are negligible in today's modern computers, which approach is considered "better" code?






Edit to clarify that this question is not a duplicate:



This question is based on the current C11 standard, which does not allow for syntax like this:



for (int i = 0; i < numRows; i++)



In C++ and C99, this syntax is perfectly acceptable whereas C11 does not allow for variable declarations inside the for statement.






Edit to correct misinformation:



I thought I was using C11 because I had recently downloaded the compiler from CodeBlocks, so that's why I said C11 didn't allow for variable declarations inside the for statement. But it turns out I was actually using C90, which was the root of my problems.


Answer



For sheer compactness and limiting of scope, I would use:




for (size_t i = 0; i < numRows; i++) {
for (size_t j = 0; j < numCols; j++) {
//
}
}


Note the use of size_t for what appear to be array indices. The size_t type is an unsigned integer type guaranteed to be able to hold any array index. Just a matter of style, but I would also suggest using braces around all loop bodies. This makes it much less likely that you will break your code with inevitable updates and changes.




By making it a habit to declare loop variables with block scope like this, you force yourself to choose to use the values stored in loop variables elsewhere in your code.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...