2011-10-17 117 views
0

我是C編程語言的新成員,並且有一個(if語句)並需要將它傳輸到switch語句中。 我的問題是,我有一個名爲(node_kind)的char *類型的字段,我用(strcmp)在if語句中比較它的內容,但我不知道如何在switch語句中這樣做。 你會告訴我如何? 這裏是我的程序的簡短報價在switch語句中使用(char *)

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; 
+2

如果是homeworo我會看看僞裝。如果不符合Paul R.的答案,並找到一種不硬編碼的方法。 – asm

回答

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: ... 
... 
} 
3

您不能使用switch語句。

但是,您可以通過使用「else if」代替第二個和第三個條件的「if」來加快代碼的執行速度。

+0

爲什麼執行速度更快? –

+1

因爲在OP的代碼中,如果第一個if語句被證明是真的,那麼他會繼續爲我們已知的其他所有情況執行strcmp。否則會導致短路。 –

4

在C中,您只能在開關盒標籤中使用整數文字常量。

對於上面的代碼示例,您應該考慮使用「數據驅動」方法,而不是將所有這些東西硬編碼到程序邏輯中。