Bál*_*Pap 6 c arrays scope const
我发现了一个有趣的事实,我不明白它是如何工作的.
以下代码完美无缺.
#include <stdio.h>
int main(){
const int size = 10;
int sampleArray[size];
typedef char String [size];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后,我试图只使用具有全局范围的常量变量,并且它仍然很好.
#include <stdio.h>
const int size = 10;
int main(){
int sampleArray[size];
typedef char String [size];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我将数组的范围也改为全局,我得到以下结果:
错误:在文件范围内修改了'sampleArray'
#include <stdio.h>
const int size = 10;
int sampleArray[size];
typedef char String [size];
int main(){
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我没有得到它!如果我将ex替换为const变量.以#define它会好起来为好.
我知道#define变量是预处理的,据我所知,const变量只是只读的.但究竟什么才能成为全球范围的?
我不明白第三段代码有什么问题,如果第二段代码还可以.
可变长度阵列可能只有自动存储持续时间.VGA在C99中引入.
不允许声明具有静态存储持续时间的VLA,因为VLA的大小是在运行时确定的(见下文)
在此标准之前,您可以使用像宏一样的宏
#define SIZE 10
//...
int a[SIZE];
Run Code Online (Sandbox Code Playgroud)
或者是枚举的枚举器
enum { SIZE = 10; }
//...
int a[SIZE];
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你可以删除const限定符,然后写
int size = 10;
Run Code Online (Sandbox Code Playgroud)
代替
const int size = 10;
Run Code Online (Sandbox Code Playgroud)
(在C++中你必须使用const限定符,尽管在C++中没有VLA,除了一些编译器可以有自己的语言扩展)
考虑到sizeofVLA 的运算符是在运行时而不是编译时计算的.