我瞭解左值的幾件事數組,但我不明白下面的代碼是如何給出一個錯誤:爲什麼foo((&i)++)給出左值需要的錯誤。有沒有相關的
#include<stdio.h>
void foo(int *);
int main()
{
int i=10;
foo((&i)++);
}
void foo(int *p)
{
printf("%d",*p);
}
6:13:錯誤:需要左值的遞增操作數 FOO(( & i)++); ^
我瞭解左值的幾件事數組,但我不明白下面的代碼是如何給出一個錯誤:爲什麼foo((&i)++)給出左值需要的錯誤。有沒有相關的
#include<stdio.h>
void foo(int *);
int main()
{
int i=10;
foo((&i)++);
}
void foo(int *p)
{
printf("%d",*p);
}
6:13:錯誤:需要左值的遞增操作數 FOO(( & i)++); ^
x ++以下步驟的結果。
1) read the value of x in to register.
2) increment the value of x
3) write the incremented value back to x (which means you are changing the value of x by '1')
但是你正在嘗試做的是(& I)++,這意味着以下。
1) read address of i into register
2) increment the address by 1
3) write the incremented value in to address again? How you can change the address?
如果要將存儲在下一個地址中的整數發送到foo(),則需要按如下方式增加。
int *p = &i + 1;
foo(p);
但是,這可能會導致未定義的行爲,因爲你只知道我存儲的值的地址。一旦你增加地址,你會得到下一個地址,它可能包含一些垃圾值。
試圖將一元運算符&
應用於臨時對象,該臨時對象的計算結果爲表達式(&i)++
。您不得將操作員應用於臨時對象。
C標準(6.5.3.2地址和間接運算符):
1 The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.
「*嘗試將一元運算符'&應用於臨時對象... *」確定? '&'適用於'i'。對我來說,看起來好像你混淆了'&'和'++'。 – alk
由於'&i'不是*左值*以及''++操作者需要一個。這大致相當於'&i = &i + 1;',最後一個表達式對你有意義嗎? –
使用變量'i'是一個左值。如果你有像'int * p =&i;'這樣的指針,那麼'p'也是一個左值。但'&我'本身*不是*左值。也許你會對[這個值類別參考]感興趣(http://en.cppreference.com/w/c/language/value_category)?請注意,[非左值表達式列表](http://en.cppreference.com/w/c/language/value_category#Non-lvalue_object_expressions)包含「地址 - 運算符」。 –
可能重複[左值需要作爲增量操作數](https://stackoverflow.com/questions/3364445/lvalue-required-as-increment-operand) – ssharma