Pass by Value and Pass by Reference

后端 未结 2 426
感动是毒
感动是毒 2021-01-22 14:22

I\'m working on a project that calculate income for employees by using overloading and also pass by value + pass by reference. I need to use at least one of the functions in pro

相关标签:
2条回答
  • 2021-01-22 15:11

    Here are some guidelines:

    • Pass by value if the value can fit into the processor's registers and the parameter will not be modified.
    • Pass by reference if the parameter will be modified by the function.
    • Pass by constant reference if the object is larger than the processor's register and the parameter will not be modified.

    Passing by constant reference for types like double, float, int, char, and bool doesn't make sense because these usually fit into the processor's word size. The compiler will try to pass these values in a register. These POD types have no additional copying costs. Thus, pass by value (less typing required).

    0 讨论(0)
  • 2021-01-22 15:13

    When you write the ampersand in the function signature, you are specifying that you are accepting a reference to the argument (in the call statement). In your function double income(const double &year) you are passing by reference because year is a reference to year.

    When you pass by value, a copy of the argument is created. When you pass by reference, a copy is not made, and your variable now has the address of the argument. So if you make a change to year in the function (assuming that it is not const for demonstrative purposes), your value in determineGross will also be changed, since the value at that address was changed.

    0 讨论(0)
提交回复
热议问题