Returning multiple values from a C++ function

后端 未结 21 2424
别跟我提以往
别跟我提以往 2020-11-22 01:04

Is there a preferred way to return multiple values from a C++ function? For example, imagine a function that divides two integers and returns both the quotient and the rema

相关标签:
21条回答
  • 2020-11-22 01:32

    Why do you insist on a function with multiple return values? With OOP you can use a class offering a regular function with a single return value, and any number of additional "return values" like below. The advantage is that the caller has a choice of looking at the extra data members, but is not required to do this. This is the preferred method for complicated data base or networking calls, where lots of additional return info may be needed in case errors occur.

    To answer your original question, this example has a method to return the quotient, which is what most callers may need, and additionally, after the method call, you can get the remainder as a data member.

    class div{
       public:
          int remainder;
    
          int quotient(int dividend, int divisor){
             remainder = ...;
             return ...;
          }
    };
    
    0 讨论(0)
  • 2020-11-22 01:32

    We can declare the function such that, it returns a structure type user defined variable or a pointer to it . And by the property of a structure, we know that a structure in C can hold multiple values of asymmetrical types (i.e. one int variable, four char variables, two float variables and so on…)

    0 讨论(0)
  • 2020-11-22 01:36

    If your function returns a value via reference, the compiler cannot store it in a register when calling other functions because, theoretically, the first function can save the address of the variable passed to it in a globally accessible variable, and any subsecuently called functions may change it, so the compiler will have (1) save the value from registers back to memory before calling other functions and (2) re-read it when it is needed from the memory again after any of such calls.

    If you return by reference, optimization of your program will suffer

    0 讨论(0)
  • 2020-11-22 01:38

    Personally, I generally dislike return parameters for a number of reasons:

    • it is not always obvious in the invocation which parameters are ins and which are outs
    • you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
    • it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
    • I like to keep my argument lists as short as possible

    I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.

    Here's another code example, this one a bit less trivial:

    pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
                                                   double planeAirspeed, double planeCourse);
    
    pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
    cout << result.first << endl;
    cout << result.second << endl;
    

    Does this print groundspeed and course, or course and groundspeed? It's not obvious.

    Compare to this:

    struct Velocity {
        double speed;
        double azimuth;
    };
    Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
                                        double planeAirspeed, double planeCourse);
    
    Velocity result = calculateResultingVelocity(25, 320, 280, 90);
    cout << result.speed << endl;
    cout << result.azimuth << endl;
    

    I think this is clearer.

    So I think my first choice in general is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.

    0 讨论(0)
  • 2020-11-22 01:38

    Use a struct or a class for the return value. Using std::pair may work for now, but

    1. it's inflexible if you decide later you want more info returned;
    2. it's not very clear from the function's declaration in the header what is being returned and in what order.

    Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.

    0 讨论(0)
  • 2020-11-22 01:39

    I tend to use out-vals in functions like this, because I stick to the paradigm of a function returning success/error codes and I like to keep things uniform.

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