c函数返回两种可能的类型之一 [英] c function to return one of two possible types

查看:38
本文介绍了c函数返回两种可能的类型之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用三种不同的函数来返回数值(一个返回一个 double ,另外两个返回一个 long ):

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;
}

这三个函数代码大约有90%相同,因此我想合并为1个函数.我想将值标志传递给单个函数,如下所示:

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. 如果传递了"1",请确定利率,并返回 double
  2. 如果"2"通过,则确定贷款期限,并返回 long
  3. 如果"3"通过,则确定贷款本金,并返回 long

在调用函数时,我只想从该函数返回1个值,但是我想返回的值可以是 double 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;
}

有一种简单的方法吗?

推荐答案

函数的返回类型在编译时是固定的.您无法根据传入的参数更改返回类型.

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

但是,由于您的主要目标是删除函数中的重复代码并将其合并,因此可以通过其他方式解决.换句话说,这是一个 XY问题.

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.

例如:

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;
}

这篇关于c函数返回两种可能的类型之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆