2014-08-28 41 views
2

我需要一些幫助來找到如何解決這個錯誤。錯誤:表達式必須有一個常數值

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"} 
}; 

如果有人能幫我理解這個非const的值...

回答

4

的錯誤是因爲全局變量初始化必須是常量表達式,但即使Menu_PowerSupply被定義爲const,它不是一個常量表達式。

這類似於:

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

在C89不編譯因爲n不是一個常量表達式。 (因爲C99支持VLA,所以它在C99中編譯)

0

不幸的是,常量表達式中不能使用常量變量。它們被認爲是不能改變的變量,但不是可以在編譯時確定的常量。

解決方法:

#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"} 
}; 
+0

一個數組的指針,那麼你就可以初始化數組不'Menu_PowerSupply'成爲多餘的嗎?!由於'MENU_PWRSPLY_NAME'&'MENU_PWRSPLY_COMMENT'被_基本替換。 – 2014-08-28 09:28:56

+0

@SaurabhMeshram這取決於'Menu_PowerSupply'是否在其他地方使用。 – user694733 2014-08-28 09:34:01

2

注意,地址全球和/或認爲編譯時間常數靜態變量。所以,如果你讓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); 
    } 
} 
相關問題