我发现了一个有趣的事实,我不明白它是如何工作的.
以下代码完美无缺.
#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变量只是只读的.但究竟什么才能成为全球范围的?
我不明白第三段代码有什么问题,如果第二段代码还可以.
#include <stdio.h>
int const NAMESIZE = 40;
int const ADDRSIZE = 80;
typedef char NameType[NAMESIZE];
typedef char AddrType[ADDRSIZE];
typedef struct
{
NameType name;
AddrType address;
double salary;
unsigned int id;
}EmpRecType;
int main(int * argc, char * argv[])
{
EmpRecType employee;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用#define而不是const它编译.这是错误:
employee.c:5:14:错误:在文件范围employee.c:6:14:错误地修改了'NameType':在文件范围内修改了'AddrType'
下面的代码片段在C中工作和编译
const int n=10;
int main(void)
{
int a[n];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,当在全局范围内声明数组时,它会引发编译错误.
const int n=10;
int a[n];
int main(void)
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么它不会在主要内部抛出错误.
我有一个游戏的头文件,声明一个2d数组的板.
#ifndef GAME_H_
#define GAME_H_
static const int columns = 15;
static const int rows = 15;
int board[rows][columns];
#endif /* GAME_H_ */
Run Code Online (Sandbox Code Playgroud)
我收到错误" error: variably modified 'board' at file scope".
在C中,const不允许使用变量声明数组大小,即使它是变量.例如:这无法在C中编译:
#include <stdio.h>
const int SIZE = 2;
int a[SIZE];
int main()
{
a[0] = 1;
a[1] = 2;
printf("%i, %i", a[0], a[1]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
$gcc -o main *.c
main.c:5:5: error: variably modified ‘a’ at file scope
int a[SIZE];
^
Run Code Online (Sandbox Code Playgroud)
但是,在C++中,它运行得很好.
在C++中运行上面的代码.
输出:
$g++ -o main *.cpp
$main
1, 2
Run Code Online (Sandbox Code Playgroud)
要使其在C中运行,必须使用#define而不是变量.即:
这在C或C++中运行得很好:
#include <stdio.h>
#define SIZE 2
// const int SIZE = 2;
int a[SIZE];
int main()
{
a[0] = 1;
a[1] = …Run Code Online (Sandbox Code Playgroud)