错误:表达式必须有一个常数值
问题描述:
我需要一些帮助来找到如何解决这个错误。错误:表达式必须有一个常数值
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的值...
答
的错误是因为全局变量初始化必须是常量表达式,但即使Menu_PowerSupply
被定义为const
,它不是一个常量表达式。
这类似于:
const int n = 42;
int arr[n];
在C89不编译因为n
不是一个常量表达式。 (因为C99支持VLA,所以它在C99中编译)
答
不幸的是,常量表达式中不能使用常量变量。它们被认为是不能改变的变量,但不是可以在编译时确定的常量。
解决方法:
#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"}
};
答
注意,地址全球和/或被认为编译时间常数静态变量。所以,如果你让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);
}
}
一个数组的指针,那么你就可以初始化数组不'Menu_PowerSupply'成为多余的吗?!由于'MENU_PWRSPLY_NAME'&'MENU_PWRSPLY_COMMENT'被_基本替换。 – 2014-08-28 09:28:56
@SaurabhMeshram这取决于'Menu_PowerSupply'是否在其他地方使用。 – user694733 2014-08-28 09:34:01