2011-09-24 23 views
0

我使用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; 

回答

4

下降分號,它是錯的

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

0

#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?)。

1

對於未來的參考,你可以通過使用-E選項的gcc查看預處理的結果。也就是,

gcc -E ex_stack1.c -o ex_stack1.i 

檢查生成的ex_stack1.i文件會使問題更加明顯。