在switch语句中使用(char *)

时间:2011-10-17 11:32:39

标签: c switch-statement strcmp

我是C编程语言的新手,有一个(if语句),需要将其转换为switch语句。 我的问题是我有一个char *类型的名为(node_kind)的字段,我使用(strcmp)在if语句中比较它的内容,但我不知道如何在switch语句中这样做。 你能告诉我怎么样? 这是我的程序的简短引用

if (strcmp(node->node_kind, "VAR_TOKEN_e") == 0) 
    job = visitor->visitjob_VAR_TOKEN; 
if (strcmp(node->node_kind, "INT_e") == 0) 
    job = visitor->visitjob_int; 
if (strcmp(node->node_kind, "BOOL_e") == 0) 
    job = visitor->visitjob_bool; 

3 个答案:

答案 0 :(得分:4)

在C中,您只能在开关案例标签中使用整数文字常量。

对于上面的代码示例,您应该考虑使用“数据驱动”方法,而不是将所有这些内容硬编码到程序逻辑中。

答案 1 :(得分:3)

您无法使用switch语句。

但是你可以通过在第二个和第三个条件中使用“else if”而不是“if”来加快代码的执行速度。

答案 2 :(得分:2)

您可以使用gperf(website)生成完美的哈希,将字符串转换为整数。你会有这样的事情:

在您的标头文件中:

enum {
    STR_VAR_TOKEN_e,
    STR_INT_e,
    STR_BOOL_e
};
int get_index(char *str);

在你的gperf文件中:

struct entry;
#include <string.h>
#include "header.h"
struct entry { char *name; int value; };
%language=ANSI-C
%struct-type
%%
VAR_TOKEN_e, STR_VAR_TOKEN_e
INT_e, STR_INT_e
BOOL_e, STR_BOOL_e
%%
int get_index(char *str)
{
    struct entry *e = in_word_set(str, strlen(str));
    return e ? e->value : -1;
}

在你的switch语句中:

switch (get_index(node->node_kind)) {
case STR_VAR_TOKEN_e: ...
...
}