【问题标题】:Converting "c99" loop to regular stuff [closed]将“c99”循环转换为常规内容[关闭]
【发布时间】:2020-01-22 13:59:18
【问题描述】:

故事:我尝试将 c99 脚本转换为常规 gcc。

问题:输出为空。

预期输出:3,2,1

length 是数组中的元素个数。

更新:该脚本旨在按降序对数组元素进行排序。

代码:

#include <stdio.h>

int main() {

    int arr[] = { 1,2,3 };
    int temp = 0;
    int length = sizeof(arr) / sizeof(arr[0]);
    int i = 0;
    int j = i + 1;

    for (i < length; i++;) {
        for (j < length; j++;) {
            if (arr[i] < arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }

    int y = 0;

    for (y < length; y++;) {
        printf("%d ", arr[y]);
    }

    return 0;
}

【问题讨论】:

  • “c99 到普通的东西”是什么意思?我在这里看不到任何特定于 C99 的内容。
  • 您的for-loop 语法错误。您正在使用预期初始化器的条件并在预期条件的位置递增。
  • 更准确地说,关于你的for循环使用,语法是可以的; 逻辑 是错误的。这将编译,但不会 执行您可能期望的操作。至少三个关于无效代码的警告应该来自这里。如果这没有发生,您需要打开警告并将其视为错误。
  • 你循环 for (y &lt; length; y++;) 很奇怪——你有一个条件,你应该有一个初始化(或者什么都没有——所以测试什么都不做),y++ 是测试条件,它失败了在第一次迭代中,因为y 在第一次迭代中为零或假,并且它是一个后增量。你所有的代码在 C90 下都是合法的,更不用说 C99 或 C11 或 C18 (除非 C90 不支持自动数组初始化——我需要研究这个,我懒得这样做,因为它已经快 20 年了无关)。
  • @JonathanLeffler 好吧,关于常量,你是对的,但是在 arr 的初始化程序中引用 arr[0] 有一些有趣的问题:stackoverflow.com/a/52309196/1848654

标签: c


【解决方案1】:

你的for循环语法的问题。

这是编写循环的正确方法。

int i, j;
for (i = 0; i < length; ++i)         // for (initialisation; test condition; operation)
{
    for (j = i + 1; j < length; ++j) // note that j is initialized with i + 1 on each iteration of 
                                     // the outer loop.  That's what makes the bubble sort work.
    {
         /* test and swap if needed */
    }
}

for (i = 0; i < length; ++i)  // note that i is reset to zero, so we can scan the array from 
                              // a known position (the top) to bottom.
{
    /* printout */
}

【讨论】:

    【解决方案2】:

    你的分号放错了位置,把它移到最左边的括号内。

    循环语法是:

    for(初始化器;中断条件;迭代器)

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2021-12-16
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多