平常看到的C语言代码中,数组的写法几乎千变一律,以至于我们以为C语言的数组就只能那么写。在C99标准中,其实说明了数组的另外一种用法,代码如下所示:
const char hello[] = {
[0] = 'h', [1] = 'e', [2] = 'l', [3] = 'l', [4] = 'o'
};
当然,还可以使用枚举值:
enum Value
{
V_0,
V_1,
V_2,
V_3,
V_4
};
const char hello[] = {
[V_0] = 'h', [V_1] = 'e', [V_2] = 'l', [V_3] = 'l', [V_4] = 'o'
};
以上这样的代码或许还不是太有意思,那么看看结构体的写法吧:
struct Type
{
int v;
};
struct Type type[] = {[0].v = 1, [1].v = 2, [2].v = 3};
哈,这样的代码是不是很有趣?用在合适的场合还是非常有用的!
代码示例:
#include
typedef void (* CmdFunc)();
enum Cmd
{
CMD_HELP = 'h',
CMD_VERSION = 'v',
};
void help_for_help();
void help_for_version();
CmdFunc CmdList[] = {
[CMD_HELP] = help_for_help,
[CMD_VERSION] = help_for_version
};
void help_for_help()
{
printf("Usage: test [options] ...\n
[-h] show help information\n
[-v] show version information");
}
void help_for_version()
{
printf("Version 1.0\n");
}
int main(int argc, char *argv[])
{
if (argc > 1 && (*argv[1] == '-'))
{
if (*(++argv[1]) == CMD_HELP || *(argv[1]) == CMD_VERSION)
{
CmdList[*argv[1]]();
}
}
return 0;
}