C/C++常量相乘初始化全局变量报Initializer element is not a compile-time constant如何解决
编译错误原因解释
C 语言标准明确要求:全局变量的初始化值必须是编译期可确定的常量表达式,不允许使用运行时才能确定值的变量参与计算。
你代码中P_year、s_year都是普通的全局double变量,即便你给它们赋值了字面量,它们本质上还是变量,不属于编译期常量,因此用二者计算P_s的初始值不符合语法要求,触发报错:
Capacitor.c:11:20: error: initializer element is not a compile-time constant
double P_s = P_year*(1/s_year);
可行的修复方案
- 方案1:将
P_s改为局部变量
局部变量的初始化没有编译期常量的限制,直接把P_s的定义移动到main函数内部即可正常运行:
#include <stdio.h> #include <math.h> //GLOBAL // Power Demand in St John's per year [GJ/yr] double P_year = 14367865E9; double s_year = 365*24*60*60;// Seconds in a year [s] //electric permitivitty of free space [s4A2/m3kg] double epsilon = 8.85418782E-12; int main(){ // Power Demand in St John's per second [GJ/yr] double P_s = P_year*(1/s_year); // Energy Required for 6hrs demand [J] double E = P_s * 60*60*6; // Voltage Difference accross capacitor [V] double V = 230E3; // Capacitance double C = 2*E/pow(V,2); printf("%f %f \n", E, C); }
- 方案2:将全局常量改为宏定义
宏是预编译期直接替换的内容,属于编译期常量,用宏定义替代变量存储固定参数即可正常初始化全局P_s:
#include <stdio.h> #include <math.h> #define P_YEAR 14367865E9 #define S_YEAR (365*24*60*60) // Power Demand in St John's per second [GJ/yr] double P_s = P_YEAR*(1.0/S_YEAR); //electric permitivitty of free space [s4A2/m3kg] double epsilon = 8.85418782E-12; int main(){ // Energy Required for 6hrs demand [J] double E = P_s * 60*60*6; // Voltage Difference accross capacitor [V] double V = 230E3; // Capacitance double C = 2*E/pow(V,2); printf("%f %f \n", E, C); }
- 方案3:延后全局变量赋值
保留P_s的全局变量属性,不在定义时初始化,改为在main函数最开头完成赋值:
#include <stdio.h> #include <math.h> //GLOBAL // Power Demand in St John's per year [GJ/yr] double P_year = 14367865E9; double s_year = 365*24*60*60;// Seconds in a year [s] // Power Demand in St John's per second [GJ/yr] double P_s; //electric permitivitty of free space [s4A2/m3kg] double epsilon = 8.85418782E-12; int main(){ P_s = P_year*(1/s_year); // Energy Required for 6hrs demand [J] double E = P_s * 60*60*6; // Voltage Difference accross capacitor [V] double V = 230E3; // Capacitance double C = 2*E/pow(V,2); printf("%f %f \n", E, C); }
额外注意事项
代码中使用了pow函数和printf函数,需要在文件最开头引入<stdio.h>和<math.h>两个头文件,否则会出现编译警告或错误。
内容的提问来源于stack exchange,提问作者STOI
相关产品推荐
相关产品推荐

