【问题标题】:expected ';', ',' or ')' before numeric constant...I'm getting this error in my C program在数字常量之前预期';',','或')'......我在我的C程序中遇到这个错误
【发布时间】:2021-01-16 00:52:30
【问题描述】:

这是我写的 C 程序 根据先前的答案,我已将变量名称从 SIZE 更改为 arrSize,但在编译代码时仍然显示错误

行:4 列:17 [错误] 数字常量前应为 ';'、',' 或 ')'

#include<stdio.h>
#include<stdlib.h>

#define arrSize 8 //I'm getting error in this line

void merge(int a[], int temp[], int left, int mid, int right);
void display(int [], int);
void msort(int [], int [], int, int);
void merge_sort(int [], const int);

int main() {
    int a[arrSize] = {-1, 2, 9, 1, 7, 2, 5, 0};
    int temp[arrSize];
    printf("Array before sorting:\n");
    display(a, arrSize);
    merge_sort(a, arrSize);
    printf("Array after sorting:\n");
    display(a, arrSize);
    return 0;
}

void merge_sort(int a[], int temp[], const int arrSize) {
    msort(a, temp, 0, arrSize-1);
}

void display(int a[], const int arrSize) {
    int i;
    for(i = 0; i < arrSize; i++) {
        printf("%d", a[i]);
        printf("\n");
    }
}

【问题讨论】:

  • edit您的帖子并添加完整的错误消息,并在需要时指出它对应的代码中的哪一行-实际上,有不止一行错误-请@987654322 @.
  • const int arrSize - 预处理器总是首先运行。它会进行令牌替换,所以它变成了const int 8。这就是为什么存在划分宏和常规标识符的命名约定的原因。
  • void merge_sort(int [], const int); 你在向你的编译器“撒谎”参数。当编译器稍后看到merge_sort 的实现时,这应该会导致错误消息。

标签: c compiler-errors c-preprocessor preprocessor-directive


【解决方案1】:

问题是,您尝试创建一个名为 arrSize 的 MACRO,然后您再次尝试在同一命名空间中使用同名变量。

基于宏名称的预处理器替换使用同名变量(标识符)在函数merge_sort()中创建无效语法。

要么更改宏名称,要么更改函数中使用的变量名称。

此外,请仔细检查函数原型和定义 - 不匹配。

【讨论】:

    【解决方案2】:

    您正在使用与常量名称一致的参数名称

    #define arrSize 8
    

    例如

    void merge_sort(int a[], int temp[], const int arrSize) {
                                                   ^^^^^^^
    

    在预处理阶段之后,编译器将这个声明视为

    void merge_sort(int a[], int temp[], const int 8) {
                                                  ^^^
    

    所以要么更改参数名称,要么更改常量名称。

    为由所有大写字母构建的清单常量分配名称是个好主意。例如

    #define ARR_SIZE 8
    

    【讨论】:

      【解决方案3】:
      • 您不能将宏和变量命名为相同的名称。 #define arrSize ... const int arrSize.
      • merge_sort 声明和定义不匹配。

      所以void merge_sort(int a[], int temp[], const int arrSize)这行是所有问题的根源。

      【讨论】:

      • 那么,我如何在函数中使用 arrSize 呢?
      • @Flame 像你一样将它作为参数传递,但给你的参数一些其他有意义的名称。
      • @Flame 一个非常常见的命名约定建议仅对宏标识符使用大写字母(和下划线),这样它们就不会与变量/参数名称冲突(混合大小写)。把它改成#define ARR_SIZE 8,你会没事的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多