无法编译固定大小的静态数组 [英] Cannot compile static array with fixed size
问题描述
#include< stdio.h>
int main()
{
const int a = 5;
static int b [a];
返回0;
}
看起来很好,呃?变量 a
是常量。
gcc -v
gcc版本6.2.1 20160830(GCC)
gcc 1.c
1.c:在函数'main'中:
1.c:6:16:error:'b'的存储大小不是常数
static int b [a ]。
顺便说一句,clang很好地编译了这段代码。
长度数组:
从 C标准:
如果一个标识符被声明为具有可变修改的
/ blockquote>
类型,它应该是一个普通的标识符(定义在
6.2.3中),没有链接,并且具有块范围或函数原型范围。 如果一个标识符被声明为
是一个具有静态或线程存储持续时间的对象,那么
不应该有一个可变长度的数组类型。
尽管长度由
const int
指定,但它不被视为常量表达式 STRONG>。即使使用static const int
类型的大小也不符合此要求。
请注意, C ++,其中
static const int
被认为是一个常量表达式。 C ++ 11还为此定义了constexpr
关键字。Minimal code example:
#include <stdio.h> int main() { const int a = 5; static int b[a]; return 0; }
Looks fine, eh? Variable
a
is constant. Works with 4.4 too.gcc -v gcc version 6.2.1 20160830 (GCC) gcc 1.c 1.c: In function ‘main’: 1.c:6:16: error: storage size of ‘b’ isn’t constant static int b[a];
Btw, clang compiles this code well.
解决方案Arrays declared as
static
or at file scope (i.e. having static storage duration) cannot be variable length arrays:From section 6.7.6.2 of the C standard:
If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.
Even though the length is specified by a
const int
, it is not considered a constant expression. Even using a size of typestatic const int
doesn't satisfy this requirement.Note that this is different in C++, where a
static const int
is considered a constant expression. C++11 also defines theconstexpr
keyword for this purpose.这篇关于无法编译固定大小的静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!