声明嵌套循环的虚拟变量的更好方法是哪种? [英] Which is the better way to declare dummy variables for nested loops?

查看:65
本文介绍了声明嵌套循环的虚拟变量的更好方法是哪种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 方法1的优点是由于源代码中的文本字符较少,因此文件大小略小:

  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++)
    //<some code here>

  • 方法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++)
        //<some code here>
    }
    

  • 即使优化的差异在当今的现代计算机中可以忽略不计,哪种方法仍被认为是更好"的代码?

    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:

    此问题基于当前的C11标准,该标准不允许使用以下语法:

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

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

    在C ++和C99中,此语法是完全可以接受的,而C11不允许在for语句内进行变量声明.

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

    编辑以纠正错误信息:

    我以为我正在使用C11,因为我最近从CodeBlocks下载了编译器,所以这就是为什么我说C11不允许在for语句中进行变量声明的原因.但是事实证明,我实际上正在使用C90,这是问题的根源.

    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.

    推荐答案

    出于纯粹的紧凑性和范围的限制,我将使用:

    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++) {
        //<some code here>
        }
    }
    

    请注意,对于似乎是数组索引的内容,请使用size_t. size_t类型是unsigned整数类型,保证可以保存任何数组索引.只是样式问题,但我还建议在所有循环主体周围使用花括号.这样就减少了因不可避免的更新和更改而破坏代码的可能性.

    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.

    这篇关于声明嵌套循环的虚拟变量的更好方法是哪种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆