const——error: variably modified ‘buf’ at file scope

来源:互联网 发布:网络电视直播哪个好 编辑:程序博客网 时间:2024/05/29 14:59

const变量在C和C++之中还是有不少区别的。在C中,const修饰的变量一般只当成“只读的”,而不是将其作为一个常量。因此如果像下面这样声明

const int SIZE;   // legal in C


不过在C++中,const修饰的变量都是常量,这和直接使用0,1,2...以及字符串”open file error!“一样,所以在声明的时候都需要赋值。

如果只是这样声明

const int SIZE;     //illegal in C++
是错误的。必须这样声明:

const int SIZE = 100;    //legal in C++

由于const修饰的变量在C中不能直接当成常量,所以如果在全局声明数组,不能使用const变量做下标。比如

const int SIZE = 100;char buf[SIZE];        // illegal in C, but legal in C++

如果在C语言这样用就会报错——error: variably modified ‘buf’ at file scope。但是如果在C++中由于SIZE会当成常量存储在堆栈特殊的位置,所以可以正确使用。


0 0