【问题标题】:struct member 'Initializer element is not a compile-time constant'struct member 'Initializer 元素不是编译时常量'
【发布时间】:2015-12-11 14:59:09
【问题描述】:
struct S {
   int a;
};

int a = ((struct S) {8}).a;

编译器报错“Initializer element is not a compile-time constant”,为什么?

【问题讨论】:

    标签: c struct initializer


    【解决方案1】:

    因为括号中的结构实际上是一个运行时的东西。您只能在初始化时将常量分配给全局。例如

     int a = 8;
    

    你不能用全局变量做到这一点:

    int b = 8;
    int a = b; // Because b is a run-time variable
    

    这种技术通常用于定义全局常量:

    #define MY_CONSTANT 8
    // Then somewhere else you can use it...
    int a = MY_CONSTANT;
    // or
    struct S s = {MY_CONSTANT};
    

    【讨论】:

    • 请注意,声明 int a = b 在函数范围内有效。只有在文件范围内声明变量才会出现错误。
    猜你喜欢
    • 2014-08-04
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    • 2011-09-02
    • 2014-02-18
    相关资源
    最近更新 更多