2017-03-06 62 views
1

我有以下代碼:爲什麼我在用const指定數組大小的const int上獲得不同的編譯器行爲?

static const int constant_int_value = 10; 
static int my_array[constant_int_value]; 

int main(void) 
{ 
    my_array[0] = 10; 
} 

鐺發出警告,但編譯它:

clang -Weverything -std=c11 array_index.c 
array_index.c:4:20: warning: variable length array used [-Wvla] 
static int my_array[constant_int_value]; 
       ^
array_index.c:4:12: warning: size of static array must be an integer constant expression [-Wpedantic] 
static int my_array[constant_int_value]; 
     ^
2 warnings generated. 

看來,我使用的是整型常量,所以我不明白的警告。

GCC不編譯的代碼:

gcc -Wall -Wextra -Wpedantic -std=c11 array_index.c 
array_index.c:4:12: error: variably modified ‘my_array’ at file scope 
static int my_array[constant_int_value]; 
+1

僅僅因爲你使用const不會使它成爲一個常量。奇怪,我知道。使用'#define constant_int_value 10' – Gab

回答

3

constant_int_value不是恆定的表達,即使const限定符和靜態存儲持續時間。你可能已經把它定義爲枚舉常數:

enum { constant_int_value = 10 }; // now, it is constant expression 

當它被放置爲陣列尺寸,編譯器假定,這是VLA。但是,VLA不允許在文件範圍(我相信它違反了約束),因此您會收到警告或錯誤。

相關問題