制作可以作为参数 &var 或 var 获取的函数

Making function that can get as parameter &var or var

本文关键字:var 获取 函数 参数      更新时间:2023-10-16

我想创建一个函数,这样我就可以双向使用它-

我知道我的措辞不好,所以我删除了它(因为它只会引起混乱),只留下里面有注释的代码:

int CalculationFunc(int i1, int i2, int i3, int i4, int i5) {
    /* Some calculation done here */
    return (i2*i3)+i5-i2+i4; /* <- this is not good example.. the calculation will be based also on
                             on values that are changing from time to time.. */
}
int main() {
// Situation 1:
    /* In this situation I didn't initialized any parameter before because I didn't
    need to.. all I need is to call to the functions with predefined values */
    int iAnswer1 = CalculationFunc(1, 2, 3, 4, 5);
    /*^ Everything is fine in this case - I Allocate memory only once*/
// ----------------------------------------------------------
// Situation 2:
    int iVal1 = 0, iVal3 = 0, iVal5 = 0; // <-- Memory is allocated 
    /* ... something done here so the values of are not constant ...
    (The code for this is not written) */

    /*In this situation something different: some values that I going to pass to the
    function are not predefined, and they are outcome of some pre-calculation done before,
    so there is allocated memory for them. If I call to the functions with these variables: */
    int iAnswer2 = CalculationFunc(iVal1, 6, iVal3, 2, iVal5);
    /* ^ There is not really a "real-world" problem here. the problem is that what happening
    In low-level is this:
        a) allocate memory for iVal1 , iVal3 , iVal5
        b) copy value of iVal1 to the allocated memory (and the same for iVal3 and iVal5)
        c) use the allocated memory..
    This is not efficient. What I want to do is to pass pointers for iVal1, iVal3, iVal5
    And the function will automatically get the data using the pointers. 
    So there will not be steps a and b.
    This is how I want to call it:
        CalculationFunc(&iVal1, 6, &iVal3, 2, &iVal5)
    */

    return 0;
}

感谢您的帮助

您可以重载函数,将不同的参数集作为引用(或纯指针),但最终会得到同一段代码的大量不必要的副本。

如果你只是为了性能而计划这样做,我建议你不要这样做。你可能不会从中获得任何性能提升,而不是使用如此简单的数据类型。

这样做更好,因为通过这种方式,函数不一定需要分配内存(仅用于复制值)来传输相同的数据。

当您通过引用或指针传递变量时,需要复制变量的地址。当您所引用的变量的数据类型为int时,地址与变量本身的大小大致相同,因此向int传递指针并不比传递int本身快。实际上,它可能更慢,因为在函数中使用值时,指针需要取消引用。

对于大小较大的数据类型,通过指针/引用传递可能会快得多,但使用int则不然。