2016-03-15 33 views
-1

我需要在我的C項目中存儲關鍵字。現在,我不得不寫保持const數據在一個地方

const char firstThingKeyword[] = "foofoofoofoo" 
const char secondThingKeyword[] = "barbarbarbar" 

的名字很長,所以我寧願引用它們

keywords.firstThing 

有沒有辦法用標準C做到這一點? (可能是GCC擴展)

我想過使用一個結構體,但是我沒有做任何事情,離開了C++舒適區。

+1

使用結構?既然這些是常量,那麼最好使用'#define'? – Evert

+0

@Evert我想過struct,但只用C++編程(不是C)對我來說有點麻煩;) – marmistrz

+2

呃,是不是'keywords.firstThing'長於'firstThingKeyword'?如果這需要多長時間纔能有明確的含義,那麼將它們縮短會使它們變得不那麼清晰。 – GManNickG

回答

3

這裏是如何做到這一點使用struct一個簡單的例子:

#include <stdio.h> 
#include <stdlib.h> 

struct _keywords { 
    const char *first; 
    const char *second; 
}; 

const struct _keywords Keywords = { 
    .first = "AAA", 
    .second = "BBB" 
}; 

int main(void) { 

    printf("first: %s\n", Keywords.first); 
    printf("second: %s\n", Keywords.second); 

    return 0; 
} 
+0

我懷疑'struct'也應該是'const'。全大寫的名稱只能用於宏或枚舉常量。 – Olaf

+0

@Olaf好的建議,我編輯了這個片段 – thelaws

相關問題