c function to return one of two possible types

  • A+
Category:Languages

I currently use three different functions to return a numeric value (one returns a double, the other two return a long):

int main(void) {    // lots of code      dRate = funcGetInterestRate();     lMonths = funcGetTerm();     lPrincipal = funcGetPrincipal();      // lots of code      return 0; } 

The three functions code is about 90% the same so I would like to consolidate into 1 function. I want to pass a value flag to a single function something like this:

  1. if "1" passed, determine interest rate, return a double
  2. if "2" passed, determine term of loan, return a long
  3. if "3" passed, determine principal of loan, return a long

I only want to return 1 value ever from the function when it is called, but the value I want to return can be either a double or a long. I want to do something like this:

void funcFunction(value passed to determine either long or double) {    // lots of code     if (foo)       return double value;    else       return long value; } 

Is there an easy way to do this?

 


A function's return type is fixed at compile time. You can't change the return type based on the parameters you pass in.

However, since your main goal is to remove repeated code in the functions and consolidate them, this can be addressed in a different way. In other words, this is an XY problem.

What you can do in your case is extract the common code in each of your three functions into a separate function, then the three original functions can call the common function to do most of the work, then extract the part they need and return that.

For example:

struct loan {     double rate;     long term;     long principal; };  void calcLoan(struct loan *loan) {     // do stuff     loan->rate = // some value             loan->term = // some value             loan->principal = // some value         }  double funcGetInterestRate() {     struct loan loan;     calcLoan(&loan);     return loan.rate; }  long funcGetTerm() {     struct loan loan;     calcLoan(&loan);     return loan.term; }  long funcGetPrincipal() {     struct loan loan;     calcLoan(&loan);     return loan.principal; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: