(原創) 如何使function傳回兩個以上的值? (C/C++) (C)
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 }
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
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 }
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
mul = 6
C++由於沒使用pointer,程式碼會比C『好看』一點,reference主要也是C++針對pointer而改進的。
See Also
(原創) 如何使function傳回多值? (使用iterator) (C#) (.NET)
Conclusion
若要回傳更多的值,就不建議用這種方式,回傳一個sturct較好。