2012-07-09 35 views
6

我想申請一元運算符'&'後面的函數來操作函數返回值。不過,我得到一個編譯時錯誤(我用gcc從MinGW的)使用一元&運算符函數返回值

test.c: In function 'main':

test.c:8:12: error: lvalue required as unary '&' operand

我做了一個代碼,使我的問題更容易理解:

int function(); 
void function2(int *param); 

main() 
{ 
    function2(&function1()); 
} 

int function1() 
{ 
    return 10; 
} 

void function2(int *param) 
{ 
    return; 
} 

此代碼創建相同的編譯時錯誤。

現在的問題是: 如何使用'&'運算符只是從function2「()」,沒有其他代碼在別處?

+2

只要'function1'返回一個'int',就不能。 – AnT 2012-07-09 15:08:52

回答

11

你想要什麼可以在C99和以後通過以下方式實現:

function2((int[]){function1()}); 

即製造複合常量,其中包含函數的返回值。

+0

這其實很聰明!實質上是創建一個臨時的「匿名」變量並將其初始化爲函數1的返回值。 – eresonance 2017-03-18 15:09:31

10

你不能。函數的返回值是一個值,但不是一個對象。它在內存中沒有指定位置,沒有地址,所以你不能指向它。相反,你可以寫:

int a = function1(); 
function2(&a); 
3

問題是,&需要變量的地址。函數的返回值不一定存儲在內存中。換句話說,它不是lvalue(你不能把它放在=的左邊)。因此,詢問其地址是沒有意義的(因爲它不存在)。

你應該做的是:

int result = function1(); 
function2(&result); 

的C11標準6.3.2.1定義lvalue爲:

An lvalue is an expression (with an object type other than void) that potentially designates an object; (footnote: The name ‘‘lvalue’’ comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue. It is perhaps better considered as representing an object ‘‘locator value’’. What is sometimes called ‘‘rvalue’’ is in this International Standard described as the ‘‘value of an expression’’)

在相同的標準,在6.5.3.2它說:

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.

+0

陳述「函數的返回值不一定存儲在變量中」是不正確的,具體地「不一定」。除非您爲要存儲的返回值指定一個變量,否則不會存儲它。 – 2012-07-09 15:11:06

+0

@nathanwhite,你是對的。我將它改爲「記憶」。 – Shahbaz 2012-07-09 15:14:04

2

您無法獲取函數返回值的地址。

如果通過CPU寄存器將該值傳回給調用者該怎麼辦?

讓function2()使用函數1()的結果的唯一方法是使用一箇中間變量,它恰好在內存中有一個地址。

main() 
{ 
    int a; 

    a = function1(); 
    function2(&a); 
} 
1

你不能直接這樣做。函數返回值可以存儲在堆棧中(並且很快將在另一個函數調用中被覆蓋),或者可能存在於寄存器等中(取決於調用約定)。

你可能不想直接訪問任何這些地方,它甚至沒有什麼意義(也許,除非你真的知道你在做什麼)。如你在編譯器輸出中看到的,'&'操作符需要一個左值(你可以賦值至)。 Ergo,只需將返回值存儲在變量('main()'中的局部變量,然後獲取它的地址)。

int main() { 
    int x = function1(); 
    function2(&x); 
}