我使用gcc版本4.3.2(Debian 4.3.2-1.1)。 我在C中編寫了一個簡單的程序來實現和測試整數堆棧。堆棧由STACK結構實現。我使用了一個名爲STACKSIZE的常量來定義堆棧的大小。 我的程序代碼如下所示:如果我在我的C程序中聲明常量爲#define或const
#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;
海合會將返回以下錯誤:
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;
海合會將返回以下錯誤:
ex_stack1.c:8: error: variably modified ‘items’ at file scope
當我用
enum {STACKSIZE=10};
GCC會成功編譯我的程序。
發生了什麼?我應該怎麼修改我的程序使用
#define STACKSIZE 10;
或
const int STACKSIZE=10;