Created
March 30, 2013 14:08
-
-
Save slembcke/5276817 to your computer and use it in GitHub Desktop.
Returning multiple values in C/C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Basically in C you only get a single return value, | |
| // but there are ways around that. | |
| // The first, and more common method is to return things using references. | |
| // Pass pointers to the output variables, and write the output values to them. | |
| // While it's common, a lot of people think it's a really bad practice (self included). | |
| void ReturnMultiple1(int a, int b, int *outX, int *outY) | |
| { | |
| // Write to the output variables. | |
| *outX = a*3 + b; | |
| *outY = a*4 - b; | |
| } | |
| void FooBar1() | |
| { | |
| int x, y; | |
| ReturnMultiple(1, 2, &x, &y); | |
| print(x, y); | |
| } | |
| // A better way in my opinion is to use a structure type (even if you only use it once). | |
| // This way the compiler can help guarantee that you actually set all the output values, | |
| // and a number of other things. The code is clearer too. | |
| // I think a lot of people don't realize you can do this. | |
| // For a number of reasons, the compiler can usually generate better machine code for this as well. | |
| // You can use a typedef too, but I usually don't. | |
| struct Vector2 { | |
| int x, y; | |
| } | |
| struct Vector2 ReturnMultiple2(int a, int b) | |
| { | |
| struct output = {a*3 + b, a*4 - b}; | |
| return output; | |
| } | |
| void FooBar() | |
| { | |
| struct Vector2 coord = ReturnMultiple2(1, 2); | |
| print(coord.x, coord.y); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment