-1

このコードの動作を理解できません。

#include<stdio.h>
void main(){
  int a,b;
  a=3,1;
  b=(5,4);
  printf("%d",a+b);
}  

出力は7です。その任務は何ですか?

4

3 に答える 3

4

コンマ演算子は、最初のオペランドを評価して結果を破棄し、次に 2 番目のオペランドを評価してこの値を返します。

実行後

a=3,1;  //  (a = 3), 1;

aがあり3、その後

b=(5,4);  // Discard 5 and the value of the expression (5,4) will be 4

bがあります4

ウィキペディアのその他の例:

// Examples:               Descriptions:                                                                   Values after line is evaluated:
int a=1, b=2, c=3, i=0; // commas act as separators in this line, not as an  operator 
                        // ... a=1, b=2, c=3, i=0
i = (a, b);             // stores b into i 
                        // ... a=1, b=2, c=3, i=2
i = a, b;               // stores a into i. Equivalent to (i = a), b;
                        // ... a=1, b=2, c=3, i=1
i = (a += 2, a + b);    // increases a by 2, then stores a+b = 3+2 into i
                        // ... a=3, b=2, c=3, i=5
i = a += 2, a + b;      // increases a by 2, then stores a to i, and discards unused
                        // a + b rvalue. Equivalent to (i = (a += 2)), a + b; 
                        // ... a=5, b=2, c=3, i=5
i = a, b, c;            // stores a into i, discarding the unused b and c rvalues
                        // ... a=5, b=2, c=3, i=5
i = (a, b, c);          // stores c into i, discarding the unused a and b rvalues
                        // ... a=5, b=2, c=3, i=3
return a=4, b=5, c=6;   // returns 6, not 4, since comma operator sequence points
                        // following the keyword 'return' are considered a single
                        // expression evaluating to rvalue of final   subexpression c=6
return 1, 2, 3;         // returns 3, not 1, for same reason as previous example
return(1), 2, 3;        // returns 3, not 1, still for same reason as above.  This
                        // example works as it does because return is a keyword, not 
                        // a function call. Even though most compilers will allow for
                        // the construct return(value), the parentheses are syntactic
                        // sugar that get stripped out without syntactic analysis 
于 2015-03-23T19:29:29.140 に答える
2
  a=3,1; // (a=3),1 -- value of expression is 1, side effect is changing a to 3
  b=(5,4);
  printf("%d",a+b); // 3 + 4
于 2015-03-23T19:29:39.913 に答える
2

この声明では

a=3,1;

代入演算子とコンマ演算子の 2 つの演算子が使用されます。代入演算子の優先度はコンマ演算子の優先度よりも高いため、このステートメントは次のようになります。

( a = 3 ), 1;

1は単純に破棄されるためa、値が割り当てられます3

この声明では

b=(5,4);

括弧があるため、コンマ演算子が最初に評価されます。その値は、最後の式 の値です4。値bが割り当てられます4

結果として、a + b => 3 + 4which equalsが得られます7

于 2015-03-23T19:33:10.057 に答える