Unable to change values in a function

后端 未结 3 902
逝去的感伤
逝去的感伤 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:12

    You need to understand that by default, C++ use a call-by-value calling convention.

    When you call swap_values, its stack frame receives a copy of the values passed to it as parameters. Thus, the parameters int x, int y are completely independent of the caller, and the variables int a, b.

    Fortunately for you, C++ also support call-by-reference (see wikipedia, or a good programming language design textbook on that), which essentially means that the variables in your function are bound to (or, an alias of) the variables in the caller (this is a gross simplification).

    The syntax for call-by-reference is:

    void swap_values( int &x, int &y ){
        // do your swap here
    }
    

提交回复
热议问题