Unable to change values in a function

后端 未结 3 906
逝去的感伤
逝去的感伤 2021-01-20 23:59

I\'m starting with developing, sorry about this newbie question.

I need to create a function that swap values between 2 vars.

I have wrote this code, but no chan

3条回答
  •  无人及你
    2021-01-21 00:14

    You need to pass the variables by reference:

    void swap_values( int& x, int& y )
    {
       int z;
       z = y;
       y = x;
       x = z;
    }
    

    pass-by-value and pass-by-reference are key concepts in major programming languages. In C++, unless you specify by-reference, a pass-by-value occurs.

    It basically means that it's not the original variables that are passed to the function, but copies.

    That's why, outside the function, the variables remained the same - because inside the functions, only the copies were modified.

    If you pass by reference (int& x, int& y), the function operates on the original variables.

提交回复
热议问题