今天在编译一段C源程序时,遇到编译错误提示 error: variably modified 'data' at file scope。原因在于代码头部有这样几行:

const int maxsize = 10000+10;
int data[maxsize];

    在C语言中,const不是一个真真正正的常量,其代表的含义仅仅是只读。使用const声明的对象是一个运行时对象,无法使用其作为某个量的初值、数组的长度、case的值或在类型的情形中使用。以上是全局的情况,那么仅在一个块中定义的情况呢?下例中const所限定的值超出其生命周期后可被修改这很容易理解不必多作解释。 

1 for(i = 0; i < 6; ++i) {
2     const int j = i; // 试试 const int j = rand();
3     printf("%d", j); // Output: 012345
4 }

    如果要在C中定义编译时常量,也就是一个真正的常量,可以使用#define宏定义,但是#define的问题在于它是直接替换源代码中的所有匹配字符串,容易造成误替换,因此对于像int型这样的情况可以耍点小把戏,就像这样:

1 enum {length = 256};  // Or: #define length 256
2 int a[length];

    那么我们经常说const也并非不可修改,利用某些小技巧可以绕过只读约束,下面的例子中被const限定的t就仍然可被修改:

1 const int t = 1;
2 *(int*)&t = 0;
3 printf("%d",t); // Output: 0

    值得注意的是,在C++中可用const修饰的变量作为数组的长度。

 

 

参考链接: http://xsk.tehon.org/den/index.php/category/tech/c-variably-modified-array-at-file-scope.html

 

相关文章:

  • 2021-12-07
  • 2022-12-23
  • 2021-04-01
  • 2021-08-11
  • 2021-10-08
  • 2021-07-28
  • 2021-12-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-23
  • 2022-12-23
  • 2021-07-29
  • 2021-09-03
  • 2022-12-23
相关资源
相似解决方案