3

次の 2 つの C ステートメントについて質問があります。

  1. x = y++;

  2. t = *ptr++;

ステートメント 1 では、y の初期値が x にコピーされ、y がインクリメントされます。

ステートメント 2 では、*ptr が指す値を調べ、それを変数 t に入れ、後で ptr をインクリメントします。

ステートメント 1 では、接尾辞インクリメント演算子が代入演算子よりも優先されます。では、最初に y をインクリメントしてから、インクリメントされた y の値に x を代入するべきではありませんか?

これらの状況での演算子の優先順位がわかりません。

4

3 に答える 3

6

の意味を誤解しています2]。ポストインクリメントは常にインクリメント前の値を生成し、その後しばらくして値をインクリメントします。

したがって、t = *ptr++本質的には次と同等です。

t = *ptr;
ptr = ptr + 1;

同じことが your にも当てはまります1]-- 得られy++た値はy、インクリメント前の の値です。優先順位はそれを変更しません-式内の他の演算子の優先順位がどれだけ高くても低くても、それが生成する値は常にインクリメント前の値になり、インクリメントは後で行われます。

于 2012-05-26T06:45:42.043 に答える
5

C のプリインクリメントとポストインクリメントの違い:

プレインクリメントとポストインクリメントは、組み込みの単項演算子です。単項とは、「入力が 1 つの関数」を意味します。「演算子」とは、「変数に変更が加えられる」ことを意味します。

インクリメント (++) およびデクリメント (--) 組み込みの単項演算子は、それらが接続されている変数を変更します。これらの単項演算子を定数またはリテラルに対して使用しようとすると、エラーが発生します。

C では、すべての組み込み単項演算子のリストを次に示します。

Increment:         ++x, x++
Decrement:         −−x, x−−
Address:           &x
Indirection:       *x
Positive:          +x
Negative:          −x
Ones_complement:  ~x
Logical_negation:  !x
Sizeof:            sizeof x, sizeof(type-name)
Cast:              (type-name) cast-expression

これらの組み込み演算子は、変数の入力を受け取り、計算結果を同じ変数に戻す変装した関数です。

ポストインクリメントの例:

int x = 0;     //variable x receives the value 0.
int y = 5;     //variable y receives the value 5

x = y++;       //variable x receives the value of y which is 5, then y 
               //is incremented to 6.

//Now x has the value 5 and y has the value 6.
//the ++ to the right of the variable means do the increment after the statement

プレインクリメントの例:

int x = 0;     //variable x receives the value 0.
int y = 5;     //variable y receives the value 5

x = ++y;       //variable y is incremented to 6, then variable x receives 
               //the value of y which is 6.

//Now x has the value 6 and y has the value 6.
//the ++ to the left of the variable means do the increment before the statement

ポスト デクリメントの例:

int x = 0;     //variable x receives the value 0.
int y = 5;     //variable y receives the value 5

x = y--;       //variable x receives the value of y which is 5, then y 
               //is decremented to 4.

//Now x has the value 5 and y has the value 4.
//the -- to the right of the variable means do the decrement after the statement

プレデクリメントの例:

int x = 0;     //variable x receives the value 0.
int y = 5;     //variable y receives the value 5

x = --y;       //variable y is decremented to 4, then variable x receives 
               //the value of y which is 4.

//x has the value 4 and y has the value 4.
//the -- to the right of the variable means do the decrement before the statement
于 2013-07-23T19:16:14.410 に答える
0
int rm=10,vivek=10;
printf("the preincrement value rm++=%d\n",++rmv);//the value is 11
printf("the postincrement value vivek++=%d",vivek++);//the value is 10
于 2014-10-09T08:23:29.250 に答える