Skip to content

Instantly share code, notes, and snippets.

@slembcke
Created March 30, 2013 14:08
Show Gist options
  • Save slembcke/5276817 to your computer and use it in GitHub Desktop.
Save slembcke/5276817 to your computer and use it in GitHub Desktop.
Returning multiple values in C/C++
// 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