c - 为什么第二个for循环不执行?

标签 c for-loop

printf调试。 while循环执行,第一个for循环执行,第二个for循环不执行。

while (size > 0){
    printf("in the while loop!\n");
    VertexPointer current = graph[0];
    int i;
    for (i = 1; i < size; i++){
        float dist = 0;
        printf("in the first for loop for i = %d \n", i);
        int j;
        for(j = 0; j++; j < dimension){
            printf("dist loop: %d\n", j);
            printf("current: %f\n", (*current).loc[0]);
            printf("unvisited: %f\n", (*graph[j]).loc[0]);

            dist = dist + pow((*current).loc[0] + (*graph[j]).loc[0], 2);
            printf("distance:  %f", dist);


            dist = sqrt(dist);
            if (dist < (*graph[i]).key){
                decreaseKey(graph, i, dist);
            }
        }

    }

    extractMin(graph, size);
    size = size - 1;
    mst_length = mst_length + (*current).key;
}

最佳答案

你切换了条件和增量:

for(j = 0; j++; j < dimension)

因此循环测试 j++ 的值,并且由于后缀 ++ 运算符返回它递增的变量的 previous 值,它将在第一次迭代时返回 0(j 的初始值),因此永远不会循环。改成

for(j = 0; j < dimension; j++)

如果您打开警告,您应该会收到一条消息,表明第三个表达式没有副作用(并且会被编译器优化掉)。


或者(停止:实际上不要这样做):

将条件更改为 ++j 以使其成为(可能)永无止境的循环:

for(j = 0; ++j; j < dimension)

如果你很幸运(在这种情况下通常是这样),循环将在 j 达到 MAX_INT 并返回到 0 时结束。但标准不会不能保证,所以它可能是无穷无尽的。

关于c - 为什么第二个for循环不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22262095/

相关文章:

c - 文件描述符、文件指针和文件位置指示符之间的关系

c - 如何在 C 中编写基于 epoll 的套接字客户端

mysql - 在 C 中关闭连接后返回函数中 MySQL 查询的结果

c - 当我只想接收单个连接时,应该如何在 C 中实现非阻塞服务器行为?

c - matlab for (递减) C语言

java - 如何检查数组中可能的除数?

C 用迭代数循环打开文件

无法理解for循环中的递归

javascript - 大 for 循环挂起 javascript 引擎

javascript - *javascript* 将所有 for 循环值提取为不同的变量