使用静态const而不是#define有什么含义?

Sim*_*ott 11 c

gcc抱怨这个:

#include <stdio.h>
static const int YY = 1024;
extern int main(int argc, char*argv[])
{  
  static char x[YY];
}
Run Code Online (Sandbox Code Playgroud)

$ gcc -c test1.c test1.c:在函数main': test1.c:5: error: storage size ofx'中不是常量test1.c:5:错误:变量`x'的大小太大

从x的定义中删除"静态",一切都很好.

我不清楚这里发生了什么:肯定YY 不变的?

我一直认为"静态const"方法比"#define"更可取.在这种情况下有没有办法使用"静态const"?

Mar*_*n B 14

在C中,const变量不是"真正的"编译时常量......它实际上只是一个你不允许修改的普通变量.因此,您无法使用const int变量来指定数组的大小.

现在,gcc有一个扩展,允许您在运行时指定数组的大小,如果在堆栈上创建数组.这就是为什么当你static从定义中x省略时,代码编译.但是,这在标准C中仍然不合法.

解决方案:使用a #define.

编辑:请注意,这是C和C++不同的一点.在C++中,a const int 一个真正的编译时常量,可用于指定数组的大小等.

  • C99允许堆栈上的可变长度数组(VLA).它不仅限于gcc. (2认同)

sam*_*wry 12

您可以使用'enum'或'define'来声明大小:

#define          XX   1024 
static int const YY = 1024;
           enum{ ZZ = 1024 };

extern int main(void){

  static char x[XX]; // no error
  *(int*)&XX = 123;  // error: lvalue required as unary ‘&’ operand


  static char y[YY]; // error: storage size of ‘y’ isn’t constant
  *(int*)&YY = 123;  // no error, the value of a const may change


  static char z[ZZ]; // no error
  *(int*)&ZZ = 123;  // error: lvalue required as unary ‘&’ operand
}
Run Code Online (Sandbox Code Playgroud)

  • 非常难看,但它起作用,副作用比#define少.它是C++"const int foo = 1024;"的C等价物. (2认同)