c - 如果我在 C 程序中用 #define 或 const 声明常量会出错

标签 c gcc

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

#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;

最佳答案

去掉分号,不对

#define STACKSIZE 10;
                    ^

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

对于 const 位,有一个 C FAQ .

The value of a const-qualified object is not a constant expression in the full sense of the term, and cannot be used for array dimensions, case labels, and the like.

关于c - 如果我在 C 程序中用 #define 或 const 声明常量会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538053/

相关文章:

c - 是否可以用c语言编程在谷歌中搜索某些内容并将第一个搜索结果显示为输出?

c - 在编译器资源管理器中包含 C 的外部头文件

c++ - 定时间隔的计算结果始终为零

c - 在未正确分配的函数中初始化的链表结构

c - 内联汇编未知

java - 在 Java 和 C 中,负数 Mod 给出负结果

c++ - openssl 加密库 - base64 转换

linux - 在自定义工具中使用 traceroute 时出现编译问题

c - 矩阵乘法控制

ubuntu - gcc/Ubuntu : Finding the disk path to the library used at linkage