2017-03-03 10 views
4

私はトークンを疑問に思っているし、どのように彼らは、コンパイラによって評価、しかし、私は構文的に文が有効で作るための基本的なトークンとしてスペースを考慮されることはありませんスペースバイナリまたは単項演算子の評価への影響

例えば。

#include<stdio.h> 
int main(){ 

     int first=1,second=3; 
     int res=first+++++second; 
     printf("%d \n",res); 
     return 0; 
} 

は、次のエラーを与える:

rough3.c:7:17: error: lvalue required as increment operand int res=first+++++second;

しかし、単純に2つの接尾辞(++)とプレフィックス(++) の間で "" を追加することによっては、正常に動作するようです。

#include<stdio.h> 
int main(){ 

     int first=1,second=3; 
     int res=first++ + ++second; 
     printf("%d \n",res); 
     return 0; 
} 

は細かい印刷物値5 は私が知りたいこのquestionいうし、未定義の動作に見てきた作品:
コンパイラが発現との間にスペースが重複しているかいないと判断したのでしょうか?
これらの式を評価するために優先順位と結合性を併用するとどうなりますか?

+3

[Maximal Munch](https://en.wikipedia.org/wiki/Maximal_munch)ルールを参照してください。 – molbdnilo

+1

これは複製です。この質問は今週初めに尋ねられ、他の質問の重複として閉鎖された。 –

+0

@molbdniloありがとうございます。 – OldMontMonk

答えて

4

4 If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token. There is one exception to this rule: header name preprocessing tokens are recognized only within #include preprocessing directives and in implementation-defined locations within #pragma directives. In such contexts, a sequence of characters that could be either a header name or a string literal is recognized as the former.

従って、この宣言の

int res=first+++++second; 

入力ストリームは、前に解析されている場合名firstを までトークン次いでfirstの次の最長の前処理トークンは++

です。

そして、次の最長前処理トークンは再び++

int res=first++ ++ +second; 
      ^^ ^^ 

などです。

したがって、これらのトークンは、この宣言は

int res= (first++)++ + second; 

のように考えられていると表現(first++)lvalueではないため、コンパイラはエラーを発行Cの文法による

int res=first++ ++ + second ; 
      ^^ ^^^^^^^^^^

を生産することになります。したがって、後置演算子++は式に適用されないことがあります。

+0

ありがとう、役立つ説明のために。 – OldMontMonk

+0

2番目のケースは、空白がトークンではないにもかかわらず空白がトークン間の区切りとして機能するため、正常にコンパイルされます。したがって、評価は次の順序で行われます。 'int res = first ++ + ++ second;' 、エラーなしでコンパイルします。 :) – OldMontMonk

2
int res=first+++++second; 

(first++)はL値ではないため

したがって
int res = (first++)++ +second; 

コンパイルエラーとして解釈されます。

しかし

int res=first++ + ++second; 

は正しい

int res = (first++) + (++second); 

として解釈されます。 C標準(6.4字句要素)によれば

+0

「+++++++++」の質問が気に入らないのですか? –

+0

答えに感謝します:) – OldMontMonk

関連する問題