代码之家  ›  专栏  ›  技术社区  ›  gil123

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

  •  -2
  • gil123  · 技术社区  · 10 年前

    我想创建一个函数,这样我可以以两种方式使用它-

    我知道我的措辞不太好,所以我删除了它(因为它只会引起混淆),只留下代码和其中的注释:

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

    谢谢你的帮助!

    1 回复  |  直到 10 年前
        1
  •  0
  •   Steadybox    10 年前

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

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

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

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

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