Cpp - Returning Multiple Values from a function

Introduction

You can get more than one value of a function via reference.

Pass two objects into the function by reference. The function then can fill the objects with the correct values.

Because passing by reference enables a function to change the original objects.

Demo

#include <iostream> 
 
enum ERR_CODE { SUCCESS, ERROR }; 
 
ERR_CODE factor(int, int&, int&); 
 
int main() /*  w ww  . j a  va2  s . co  m*/
{ 
    int number = 2, squared, cubed; 
    ERR_CODE result; 
 
    result = factor(number, squared, cubed); 
 
    if (result == SUCCESS) 
    { 
          std::cout << "number: " << number << "\n"; 
          std::cout << "square: " << squared << "\n"; 
          std::cout << "cubed: "  << cubed   << "\n"; 
    } 
    else 
    { 
        std::cout << "Error encountered!!\n"; 
    } 
    return 0; 
} 
 
ERR_CODE factor(int n, int &rSquared, int &rCubed) 
{ 
    if (n > 20) 
    { 
        return ERROR;   // simple error code 
    } 
    else 
    { 
          rSquared = n * n; 
          rCubed = n * n * n; 
          return SUCCESS; 
    } 
}

Result

Related Topic