C: For 循环:为什么 "z" 的循环继续条件与 "z > 0" 的循环条件相同,但 z-- 递减?

C: For Loop: Why does a loop-continuation condition of "z" work the same as "z > 0"with a decrement of z--?

完全披露:我想我已经通过将所有这些形式化来回答了我自己的问题。请你检查一下我的逻辑吗?

使用以下术语: for(初始化控制变量;循环继续条件[布尔表达式];de/increment)

我写了一个打印出马里奥风格金字塔的循环:

    Welcome to Super Mega Mario! 
    Height: 5
        #  #
       ##  ##
      ###  ###
     ####  ####
    #####  #####

在代码中,我使用了两种不同的循环继续条件:

for (int z = i + 1; z > 0 ; z--)
for (int z = i + 1; z ; z--)

我不确定为什么第二个例子有效,下面是我试图解释的。

为什么我认为这两种方法都有效:

第一个例子 (z > 0):

要打印最后一行##### #####,for 函数打印“#”5 次。首先,因为 z == 5,所以 Bool 为真,所以打印“#”。那么z == 4,Bool为真,所以打印“#”。这继续 直到 z == 0,所以 Bool 为 FALSE,所以 break.

第二个例子(z):

所有非零值都为真,z为5,4,3,2,1。当 z 为 0 (FALSE) 时,中断。

我正在学习,我想开发优秀的风格和设计,如果你能解释一下哪个例子设计得更好,请告诉我!另外,如果您可以推荐我的风格的编辑,那么也请 HMU。 [源代码@结束].

    int main(void)
    {
        int n;//Declare variables outside of loops to allow "while" function to use it.
        printf("Welcome to Super Mega Mario! \n");
        do
        {
            n = get_int("Height: "); //prompt user for height of pyramid.
        }
        while (n < 1 || n > 8);
        for (int i = 0; i < n; i++)//How many rows will be created
        {
            for (int j = 0; j < n; j++) //column
            {
                for (int x = n - i - 1; x; x--) //for(initialise control variable; loop continuation condition [boolean expression]; increment)
                {
                    printf(" ");
                }
                for (int y = i + 1; y; y--) //If the loop continuation condition is y, then it's TRUE. So the function will run. Then it decreases this value by 1, so it's now 0 or FALSE so the function breaks.
                {
                    printf("#");
                }
                printf("  ");
                for (int z = i + 1; z > 0 ; z--) //In theory "z>0" works the same as z on its own.
                {
                    printf("#");
                }
                break;
            }
            printf("\n");
        }
    }
表达式中的

z 等同于 z != 0。当放置在表达式中时,所有 non-zero 值(正或负)都将被视为布尔值 true。类似地,给定一个指针 int* p; 那么 if(p) 等价于 if(p != NULL).


if you can explain which example is better designed, please let me know!

  • 风格是主观的,尽管通常被认为是明确的更好的风格,因为它给出了 self-documenting 代码并排除了拼写错误。如果我输入 if(p != NULL) 那么就不会误解我的意思。但是,如果我键入 if(p),那可能就是我的意思,或者当我实际上想要 de-reference 指针 if(*p).

    时,它可能是一个错误
  • 关于样式的主题,通常最好使 for 循环尽可能简单。这意味着避免在 3 个 for 子句中使用不必要的复杂表达式,并尽可能执行 up-counting 循环。 for 循环的惯用形式是:

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

    我们应该努力争取尽可能接近那个。例如,在 for (int z = i + 1; z > 0 ; z--) 的情况下,您迭代的顺序无关紧要,因此 down-counting 只是混淆。没有理由不应该写成 for(int z=0; z<i; z++).

  • 还有风格:无论你使用哪种大括号放置风格,总是将 do while 中的 while 与 [=26= 写在同一行是惯例].即:} while (n < 1 || n > 8);

  • 此处存在错误:break; 多次阻止 for (int j = 0; j < n; j++) 循环 运行。