2014-10-06 114 views
2

考慮語法,實現C風格的類型聲明的語法歧義:證明類型聲明語法

Declaration ::= Type Declarator ; 

     Type ::= int | char 

Declarator ::= * Declarator 

       | Declarator [ num ] 

       | Declarator (Type) 

       | (Declarator) 

       | name 

我必須證明句法歧義。我很難識別它是模棱兩可的情況。這裏是所有的下列情況下,我想出了滿足語法:

  • int * Declarator;
  • char * Declarator;
  • int Declarator[num];
  • char Declarator[num];
  • int Declarator(type);
  • char Declarator(type);
  • int Declarator;
  • char Declarator;
  • int name;
  • char name;

什麼我沒有看到嗎?

+0

'Declarator'是一個非終端,就像'type'一樣。你不應該把'Declarator'放在你想分析的字符串中,你必須將它減少到一系列終端。 – 2014-10-06 07:00:59

+1

是什麼讓你覺得它是模糊的? – 2014-10-06 08:01:17

回答

3

int *something[3]是一個三指針數組還是一個指向三個int數組的指針? int **something[3]怎麼樣?

C標準的附錄A A簡化了的C語法包括:

(Many productions omitted) 
declarator: pointeropt direct-declarator 
pointer: '*' 
     | '*' pointer 
direct-declarator: identifier 
        '(' declarator ')' 
        direct-declarator '[' assignment-expressionopt ']' 

那如何解決上述不確定性?

另外,考慮表達*a[3]和聲明int *a[3]。在表達式中,後綴限定符[3]優先於前綴限定符*,這是表達式的正常模式。這與聲明的語法是如何比較的?爲什麼做出這個決定?