我正在尝试学习 C,但在以下代码中出现错误。
如果我使用 半径 在卷中我收到一个错误:error #2069: Initializer must be constant.
#include <stdio.h>
#define PI (3.14)
/* Define radius*/
int radius = 10;
float volume = ( 4.0f / (3.0f * PI * radius) );
int main(void){
return 0;
}
但是当我用一个实际数字改变半径时,它编译得很好。
#include <stdio.h>
#define PI (3.14)
/* Define radius*/
int radius = 10;
float volume = ( 4.0f / (3.0f * PI * 10) );
int main(void){
return 0;
}
为什么会发生这种情况,我该怎么做才能使第一个版本正常工作?
最佳答案
在 C 中,您不能使用非常量表达式初始化全局变量。
C99 标准:第 6.7.8 节:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
在您的示例中,
volume
是一个全局变量,具有静态存储持续时间和 radius
不是常数。因此错误。
关于c - 初始化程序必须是常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14414480/