c++ - 混淆条件的评估和 for 循环的步骤

标签 c++ c for-loop step-into

void draw_diamond(int n)
{
int mid_pos = ceil((double)n / 2);
int left_spaces = mid_pos-1;
int line_stars = 1;

putchar(10);
//printing from top through the middle of the diamond
for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
{
    //printing the left_spaces
    for(int i=1; i<=left_spaces; i++)
        putchar(32);

    //printing the line_stars
    for(int i=1; i<=line_stars; i++)
        putchar('*');
    putchar(10);
}

...

我这里有问题,当我第一次 step into for loop 时,没有任何反应,因为第二次 for loop step 例如:如果我 将 1 传递给 n 那么:

mid_pos =1; 左空格=0; line_stars=1;

它进入循环: 左空格=-1; line_stars=3;

for 循环 打印了 3 颗星,但它应该只打印 1 颗星。

我很困惑,如果有人能提供帮助,我将不胜感激。

最佳答案

哦哦,注意偷偷摸摸的分号:

for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
                                                                            ^
                                                                            |

这将结束您的 for 语句。循环将一直运行到 line_stars 大于 n 为止。到最后,line_stars 现在将等于 3(因为它增加了 2)。 left_spaces 将为 -1。

现在将执行用大括号括起来的其余代码。第一个 for 循环根本不会运行,但第二个循环将从 1 运行到 line_stars 并且,正如我们所知,line_stars 是3,所以我们打印出 3 颗星。

关于c++ - 混淆条件的评估和 for 循环的步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14034940/

相关文章:

c - 有没有C的子集可以这样写: i=+1?

c++ - 你不能用双指针引用二维数组吗?

c++ - 以管理员身份运行 Visual Studio 时,Visual Studio 2008 中是否存在使用 C++ 中的放置目标的已知错误?

c - 为什么我的 ppm 文件中的图像有点偏差?

java - 捕获异常后 for 循环继续出现问题

c++ - 在循环中创建 100 个具有不同名称的对象

c - 循环操作

c++ - 生成算术运算结果类型的策略?

c++ - 非捕获 lambda 生命周期

c++ - 如何在 Doxygen 内联代码中转义特殊命令