(原創) 如何使function傳回兩個以上的值? (C/C++) (C)

來源:互聯網
上載者:User

Abstract
若要使function傳回一個值,可以使用return,若要傳回兩個以上的值呢?

Introduction
要使function傳回兩個以上的值,方法還不少,最簡單的方式是使用pass by address / pass by reference。

一個很簡單的需求,傳入兩個整數後,希望同時傳回相加與相乘的結果。

C語言

 1 /* 
 2 (C) OOMusou 2008 http://oomusou.cnblogs.com
 3 
 4 Filename    : fuction_return_two_value.c
 5 Compiler    : Visual C++ 8.0
 6 Description : Demo how to return 2 value by C
 7 Release     : 03/15/2008 1.0
 8 */
 9 
10 #include <stdio.h>
11 
12 void func(int x, int y, int *sum, int *mul) {
13   *sum = x + y;
14   *mul = x * y;
15 }
16 
17 int main() {
18   int x = 2;
19   int y = 3;
20   int sum;
21   int mul;
22   
23   func(x, y, &sum, &mul);
24   
25   printf("sum = %d\n", sum);
26   printf("mul = %d\n", mul);
27 }

執行結果

sum = 5
mul = 6

由於return只能回傳單一值,所以不能使用return,但只要使用兩個pass by address的方式,就可以回傳兩個以上的值。

在C++就有點不同了,因為C++提出了reference觀念,所以可以不用pointer。

C++
 1 /* 
 2 (C) OOMusou 2008 http://oomusou.cnblogs.com
 3 
 4 Filename    : fuction_return_two_value.cpp
 5 Compiler    : Visual C++ 8.0
 6 Description : Demo how to return 2 value by C++
 7 Release     : 03/15/2008 1.0
 8 */
 9 
10 #include <iostream>
11 
12 using namespace std;
13 
14 void func(int const x, int const y, int &sum, int &mul) {
15   sum = x + y;
16   mul = x * y;
17 }
18 
19 int main() {
20   int x = 2;
21   int y = 3;
22   int sum;
23   int mul;
24   
25   func(x, y, sum, mul);
26   
27   cout << "sum = " << sum << endl;
28   cout << "mul = " << mul << endl;
29 }

執行結果sum = 5
mul = 6

C++由於沒使用pointer,程式碼會比C『好看』一點,reference主要也是C++針對pointer而改進的。

See Also
(原創) 如何使function傳回多值? (使用iterator) (C#) (.NET)

Conclusion
若要回傳更多的值,就不建議用這種方式,回傳一個sturct較好。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.