【问题标题】:Error if i declare constant with #define or const in my C program如果我在 C 程序中使用 #define 或 const 声明常量,则会出错
【发布时间】:2011-09-24 09:05:16
【问题描述】:

我使用 gcc 版本 4.3.2 (Debian 4.3.2-1.1)。 我用 C 编写了一个简单的程序来实现和测试整数堆栈。堆栈由 STACK 结构实现。我使用了一个名为 STACKSIZE 的常量来定义堆栈的大小。 我的程序代码如下所示:

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

#define STACKSIZE 10;

typedef struct {
    int size;
    int items[STACKSIZE];
} STACK;

void push(STACK *ps, int x)
{
    if (ps->size == STACKSIZE) {
        fputs("Error: stack overflow\n", stderr);
        abort();
    } else
        ps->items[ps->size++] = x;
}

int pop(STACK *ps)
{
    if (ps->size == 0){
        fputs("Error: stack underflow\n", stderr);
        abort();
    } else
    return ps->items[--ps->size];
}

int main() {
    STACK st;
    st.size = 0;
    int i;
    for(i=0; i < STACKSIZE + 1; i++) {
        push(&st, i);
    }
    while(st.size != 0)
        printf("%d\n", pop(&st));
    printf("%d\n", pop(&st));
    return 0;
}

当我使用 #define STACKSIZE 10; gcc 将返回以下错误:

ex_stack1.c:8: error: expected ‘]’ before ‘;’ token
ex_stack1.c:9: warning: no semicolon at end of struct or union
ex_stack1.c: In function ‘push’:
ex_stack1.c:13: error: expected ‘)’ before ‘;’ token
ex_stack1.c:17: error: ‘STACK’ has no member named ‘items’
ex_stack1.c: In function ‘pop’:
ex_stack1.c:26: error: ‘STACK’ has no member named ‘items’
ex_stack1.c: In function ‘main’:
ex_stack1.c:33: error: expected ‘)’ before ‘;’ token

我用的时候

const int STACKSIZE=10;

gcc 将返回以下错误:

ex_stack1.c:8: error: variably modified ‘items’ at file scope

我用的时候

enum {STACKSIZE=10};

gcc 会成功编译我的程序。

发生了什么?我应该如何修改我的程序以使用

#define STACKSIZE 10;

const int STACKSIZE=10;

【问题讨论】:

    标签: c gcc


    【解决方案1】:

    去掉分号,错了

    #define STACKSIZE 10;
                        ^
    

    如果你保留它,预处理器会将int items[STACKSIZE]; 翻译成明显错误的int items[10;];

    对于const 位,有一个C FAQ

    一个 const 限定对象的值 不是一个常量表达式 该术语的完整含义,不能用于数组维度, 案例标签等。

    【讨论】:

      【解决方案2】:

      为了将来参考,您可以通过使用 gcc 的 -E 选项来查看预处理器的结果。也就是说,

      gcc -E ex_stack1.c -o ex_stack1.i 
      

      检查生成的 ex_stack1.i 文件会使问题更加明显。

      【讨论】:

        【解决方案3】:

        #define 进行文本替换。既然你有:

        #define STACKSIZE 10;
        

        然后

        typedef struct {
            int size;
            int items[STACKSIZE];
        } STACK;
        

        变成:

        typedef struct {
            int size;
            int items[10;];
        } STACK;
        

        在 C 中,const 用于声明不能(轻松)修改的变量。它们不是编译时常量。

        enum 但是,确实定义了一个编译时常量。一般来说,您应该尽可能选择enum 而不是const int 而不是#define。 (见Advantage and disadvantages of #define vs. constants?)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-21
          • 2018-07-12
          相关资源
          最近更新 更多