Returning multiple values from a C function

前端 未结 11 984
醉话见心
醉话见心 2021-01-18 08:05

Important: Please see this very much related question: Return multiple values in C++.

I\'m after how to do the same thing in ANSI C? Would you use a

相关标签:
11条回答
  • 2021-01-18 08:57

    This depends massively on your architecture, and also if you expect (or can have) the function inlined. I'd first write the code in the simplest way, and then worry about speed if that shows up as an expensive part of your code.

    0 讨论(0)
  • 2021-01-18 08:58

    Both ways are valid, certianly, but I would would consider the semantics (struct vs parameter reference) to decide which way best communicates you intentions to the programmer.

    If the values you are returning are tightly coupled, then it is okay to return them as a structure. But, if you are simply creating artificial mechanism to return values together (as a struct), then you should use a parameter reference (i.e. pass the address of the variables) to return the values back to the calling function.

    0 讨论(0)
  • 2021-01-18 09:02

    I would pass the address to a struct. If the information to be returned isn't complex, then just passing in the addresses to the values would work too.

    Personally, it really comes down to how messy the interface would be.

    void SomeFunction( ReturnStruct* myReturnVals )
    {
      // Fill in the values
    }   
    
    // Do some stuff    
    ReturnStruct returnVals;
    SomeFunction( &returnVals);    
    // Do more stuff
    
    0 讨论(0)
  • 2021-01-18 09:04

    Easiest to read should be passed addresses in the function, and it should be fast also, pops and pushes are cheap:

    void somefunction (int inval1, int inval2, int *outval1, int *outval2) {
       int x = inval1;
       int y = inval2;
    // do some processing
       *outval1 = x;
       *outval2 = y;
       return;
    }
    
    0 讨论(0)
  • 2021-01-18 09:04

    In either case, you're passing references, so performance should be similar. If there is a chance that the function never actually returns a value, you could avoid the cost of the malloc with the "return a struct" option since you'd simply return null.

    My personal preference is to return a dynamically allocated (malloc'd) struct. I avoid using function arguments for output because I think it makes code more confusing and less maintainable in the long-term.

    0 讨论(0)
提交回复
热议问题