Search code examples
c++functionparametersreference

C++: Argument Passing "passed by reference"


I understand as with any other variable, the type of a parameter determines the interaction between the parameter and its argument. My question is that what is the reasoning behind why you would reference a parameter vs why you wouldn't? Why are some functions parameters reference and some are not? Having trouble understanding the advantages of doing so, could someone explain?


Solution

  • Passing by reference has two purposes:
    1. To modify the value of a function's argument
    2. To avoid copying an object, which leads to poor performance.

    Example of modifying the argument

    void get5and6(int *f, int *s)  // using pointers
    {
        *f = 5;
        *s = 6;
    }
    

    this can be used as:

    int f = 0, s = 0;
    get5and6(&f,&s);     // f & s will now be 5 & 6
    

    OR

    void get5and6(int &f, int &s)  // using references
    {
        f = 5;
        s = 6;
    }
    

    this can be used as:

    int f = 0, s = 0;
    get5and6(f,s);     // f & s will now be 5 & 6
    

    When we pass by reference, we pass the address of the variable. Passing by reference is similar to passing a pointer - only the address is passed in both cases.

    For eg:

    void SaveGame(GameState& gameState)
    {
        gameState.update();
        gameState.saveToFile("save.sav");
    }
    
    GameState gs;
    SaveGame(gs)
    

    OR

    void SaveGame(GameState* gameState)
    {
        gameState->update();
        gameState->saveToFile("save.sav");
    }
    
    GameState gs;
    SaveGame(&gs);
    

    Since only the address is being passed, the value of the variable (which could be really huge for huge objects) **doesn't need to be copied**. So passing by reference improves performance especially when:
    1. The object passed to the function is huge (I would use the pointer variant here so that the caller knows the function might modify the value of the variable)
    2. The function could be called many times (eg. in a loop)

    Also, read on const references. When it's used, the argument cannot be modified in the function.