Download

Returning and capturing multiple values from function.

Hi all. I’m planning on making the switch from Blueprints to C++ and I’m wondering how you might have a C++ only function with multiple return values, something that is trivial to do in Blueprints. Do you just have to declare a custom struct outside of the function and set that as the return type, or are there other ways to do it? Thanks!

Hi ausernottaken
Yes, it is also trivial in c++ you have to use references like this:



UFUNCTION(BlueprintCallable, Category = "Example")
void MultipleReturns(float& floatBack, int32& intBack); // like this


Now you will notice that you lost the reference, but what happen if you really want the reference???, then use this:



UFUNCTION(BlueprintCallable, Category = "Example")
void MultipleRealReferences(UPARAM(ref) float& floatRef, UPARAM(ref) int32& intRef); // like this


Hey ZkarmaKun, thanks for the response! I noticed that your example function has the BlueprintCallable metadata specifier. I am aware that Blueprint functions written in C++ can have multiple outputs, but does this also work when the function is called in C++? If so, how do you capture the returned values? Are you passing in a pointer to the variable and modifying it directly, rather than returning a copy?

Yes, that’s exactly it. Here’s some example code using pointers:



void SomeFunction()
{
   uint32 a = 0;
   uint32 b = 0;

   ReturnFiveAndSix(&a, &b);

   // a = 5, b = 6 now
}

void ReturnFiveAndSix(uint32 * OutOne, uint32 * OutTwo)
{
   *OutOne = 5;
   *OutTwo = 6;
}


hi again
yes like jaffob said, it is a common practice, also there is another reason, lets say that you have heavy operations in a function, you dont want a extra copy every time specially in TArrays, you can pass the reference and make your opp then, one of the reasons why c++ is better, more control of every byte

Makes perfect sense. Thanks for your help!