2011-10-18 91 views
3

非常簡單的問題其中這樣的代碼工作嗎?C數組初始化範圍

static void *gostruct[] = 
{ 
    [0 ... 255] = &&l_bad, 
    ['\t'] = &&l_loop, [' '] = &&l_loop, ['\r'] = &&l_loop, ['\n'] = &&l_loop, 
    ['"'] = &&l_qup, 
    [':'] = &&l_loop,[','] = &&l_loop, 
    ['['] = &&l_up, [']'] = &&l_down, // tracking [] and {} individually would allow fuller validation but is really messy 
    ['{'] = &&l_up, ['}'] = &&l_down, 
    ['-'] = &&l_bare, [48 ... 57] = &&l_bare, // 0-9 
    ['t'] = &&l_bare, ['f'] = &&l_bare, ['n'] = &&l_bare // true, false, null 
}; 

通過它其讀數清晰地看到,它含有初始化256項的數組的值& & l_bad然後覆蓋具有特定值某些索引。但是這個代碼不能在VS2010中編譯,這是我可以訪問的,所以我想知道這是有效的C代碼。

注意:此代碼片段取自JSON parser on github,據我瞭解,該代碼片段爲處理JSON字符串創建跳轉表。

+0

我相信這是使用gcc擴展。 – Angelom

回答

5

該構建體被稱爲Designated Initializers
在指定的初始化程序中使用範圍是一個GNU gcc特定的擴展。

要初始化範圍內的元素爲相同的值,寫入[first ... last] = value 。這是一個GNU擴展。例如,

int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 

-pedantic編譯它會告訴你。
請注意,它是不可移植的,因爲它是編譯器特定的擴展。

+1

指定的初始化程序不是gcc擴展(gcc允許它們在C89模式下),但是在指定的初始化程序中使用'...'是。 –

+0

謝謝,在大多數搜索引擎中搜索這種語法都相當困難,因此非常感謝。 – James

3

這是使用數字GNU C擴展。

http://www.gnu.org/s/gnu-c-manual/gnu-c-manual.html

'as a GNU C extension, you can initialize a range of elements 
to the same value, by specifying the first and last indices, in the 
form [first] ... [last]' 

'As a GNU C extension, you can also take the address of a label 
with the label address operator &&. The result is a void* pointer 
which can be used with goto.' 

它看起來這是最有可能被用來作爲一個解析器, 即整個節將需要重寫,如果你打算將它移植到Windows跳轉表。

你可能會發現,你將實現一個簡單的switch語句和替換 查找和跳轉跳躍,像Perl中會幫助你的「輸入」 excersise :)在指定的初始

+0

+1瞭解更多有用信息。 – James

+0

'&&'正在殺死我!謝謝! – Guido

1

使用範圍是一個gcc擴展,在標準C99中不支持。

此外代碼需要標籤的地址,我相信它也是gcc擴展名。

所以,這不是有效的C代碼,只是有效的gcc c代碼。

1

根據參考文獻

在ISO C99可以給任何順序的元素,指定數組索引或結構字段名它們適用於,和GNU C允許此作爲C90模式的擴展作爲好。這個擴展沒有在GNU C++中實現。

範圍和特定初始值設定項都支持ISO C99,不僅是GNU擴展。您可以嘗試在Visual Studio 2010中啓用ISO C99(我不知道如何)。

參考:https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html