下面是一段代碼,完美地執行C.
int a=3,b=4,x,y;
x=a+b;
y=a*b;
return(x,y);
該函數返回12.可有人請解釋。
下面是一段代碼,完美地執行C.
int a=3,b=4,x,y;
x=a+b;
y=a*b;
return(x,y);
該函數返回12.可有人請解釋。
這是因爲您(無意中)使用的comma operator,其值是包含的最後一個表達式的值。您可以按照自己的喜好列出儘可能多的表達式,用逗號分隔符分隔,結果始終是最後一個表達式的結果。這與return
無關;你的代碼可以改寫像
int tmp = (x, y); // x = 7, y = 12 -> tmp is assigned 12
return tmp;
[更新]您通常不需要周圍的名單括號,但在這裏,你這樣做,由於具有比逗號更高的優先級賦值運算符 - 榮譽給@Draco指出它。
@Draco,你是對的,謝謝:-)我相應地更新了我的答案。 – 2010-09-02 14:43:32
你的問題的答案是「不,返回不能返回多個值」。在這裏,你看到的法律表現x,y
,這是y
即3 * 4 = 12
編輯的評估結果:這回答標題Q,即「可以返回返回多個值」 不完全是。可以
這就是一個實例逗號運算符。它評估其左側,然後評估其右側,其結果值是右側。
因此,return(x,y)
與return y
相同,因爲評估x
沒有副作用。
在C「返回多個值」的唯一方法是通過值返回一個struct:
#include <stdio.h>
typedef struct {
int sum;
int product;
} sumprod;
sumprod get_sum_and_product(int x, int y) {
sumprod ret = {x + y, x * y};
return ret;
}
int main() {
sumprod values = get_sum_and_product(3,4);
printf("sum is %d, product is %d\n", values.sum, values.product);
}
的comma operator僅僅是一個二元運算符。返回最右邊的值。
不,你不能簡單地用(x, y)
返回多個值 - 這不是一個元組,你可能從其他語言的期望,但括號使用comma operator,哪隻會計算爲y
(這將反過來,由return
返回)。
如果你想返回多個值,你應該create a struct
,就像這樣:
#include <stdio.h>
struct coordinate
{
int x;
int y;
};
struct coordinate myfunc(int a, int b)
{
struct coordinate retval = { a + b , a * b };
return retval;
}
int main(void)
{
struct coordinate coord = myfunc(3, 4);
printf("X: %d\n", coord.x);
printf("Y: %d\n", coord.y);
}
這顯示了使用一個結構完整的語法,但你可以use typedef
如果你喜歡這樣的:
typedef struct
{
int x;
int y;
} coordinate;
coordinate myfunc(int a, int b)
{
coordinate retval = { a + b , a * b };
return retval;
}
// ...etc...
你似乎在這裏問兩個不同的問題。 – BoltClock 2010-09-02 11:31:00
感覺像y ?! :) – 2010-09-02 11:31:29
哪個C編譯器? – 2010-09-02 11:32:01