【问题标题】:error: expression must have a constant value错误:表达式必须有一个常量值
【发布时间】:2014-10-21 22:06:04
【问题描述】:

我需要一些帮助来解决这个错误。

typedef struct {
    const char *iName;
    const char *iComment;
} T_Entry;

const T_Entry Menu_PowerSupply = { "PWRS", "Power supply"};

static const T_Entry G_Commands[] = {
    { "MEM", "Memory"},
    {Menu_PowerSupply.iName,Menu_PowerSupply.iComment},
    { "SYS", "System"}
};

我得到了错误:表达式必须有一个常数值 我该如何解决这个问题?

对我来说,在链接时间是已知的,并且在具有固定值的固定地址:我错了


我的目的是将以下代码放入库中

const T_Entry Menu_PowerSupply = { "PWRS", "Power supply"};

以下也不起作用

static const T_Entry G_Commands[] = {
    { "MEM", "Memory"},
    Menu_PowerSupply,
    { "SYS", "System"}
};

如果有人可以帮助我理解这个 non const 值...

【问题讨论】:

    标签: c arrays compiler-errors constants


    【解决方案1】:

    请注意,全局和/或静态变量的地址被视为编译时常量。因此,如果您将G_Commands 设为指针数组,则可以如下所示初始化数组

    typedef struct
    {
        const char *iName;
        const char *iComment;
    }
        T_Entry;
    
    const T_Entry EntryMemory      = { "MEM" , "Memory"       };
    const T_Entry EntryPowerSupply = { "PWRS", "Power supply" };
    const T_Entry EntrySystem      = { "SYS" , "System"       };
    
    static const T_Entry *G_Commands[] =
    {
        &EntryMemory,
        &EntryPowerSupply,
        &EntrySystem,
        NULL
    };
    
    static const T_Entry *G_Menus[] =
    {
        &EntryPowerSupply,
        NULL
    };
    
    int main( void )
    {
        const T_Entry **entry, *command, *menu;
    
        printf( "Commands:\n" );
        for ( entry = G_Commands; *entry != NULL; entry++ )
        {
            command = *entry;
            printf( "   %-4s %s\n", command->iName, command->iComment );
        }
    
        printf( "\nMenus:\n" );
        for ( entry = G_Menus; *entry != NULL; entry++ )
        {
            menu = *entry;
            printf( "   %-4s %s\n", menu->iName, menu->iComment );
        }
    }
    

    【讨论】:

      【解决方案2】:

      很遗憾,常量变量不能用于常量表达式。它们被认为是不能改变的变量,而不是可以在编译时确定的常量。

      解决方法:

      #define MENU_PWRSPLY_NAME    "PWRS"
      #define MENU_PWRSPLY_COMMENT "Power supply"
      
      const T_Entry Menu_PowerSupply = { MENU_PWRSPLY_NAME, MENU_PWRSPLY_COMMENT };
      
      static const T_Entry G_Commands[] = {
          { "MEM", "Memory"},
          { MENU_PWRSPLY_NAME, MENU_PWRSPLY_COMMENT },
          { "SYS", "System"}
      };
      

      【讨论】:

      • Menu_PowerSupply 在这里不是多余的吗?!因为MENU_PWRSPLY_NAME & MENU_PWRSPLY_COMMENT基本上被替换了。
      • @SaurabhMeshram 这取决于Menu_PowerSupply是否在其他地方使用。
      【解决方案3】:

      错误是因为全局变量的初始化器必须是常量表达式,但是即使Menu_PowerSupply被定义为const,它也不是常量表达式。

      这类似于:

      const int n = 42;
      int arr[n]; 
      

      在 C89 中无法编译,因为 n 不是常量表达式。 (它在 C99 中编译只是因为 C99 支持 VLA)

      【讨论】:

        猜你喜欢
        • 2021-12-02
        • 2012-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 2021-01-14
        相关资源
        最近更新 更多