C++ basic difference between call by value (cbv) and call by reference (cbr).

in #programming7 years ago (edited)

I noticed that some people in my class get trouble with CBV and CBR, and also some people on the internet.
So here's a short summery.

CBV and CBR are different kinds to send variables or values to a function.

CBV means that your are sending a COPY to the function. So the original variable doesn't change.
CBR means that your are sending a REFERENCE to the function. This means that your are working with the original variable.

A code example:

Main function:

As you can see, there are two CBR-functions.
This is possible, because in our function we can use either the reference operator (&) or the pointer operator(*).

In a nutshell you can say:
'& 'is the reference operator and can be read as “address of”.
'*' is the dereference operator and can be read as “value pointed by”.

Pointers are mainly used to send an array to a function. But also for memory management and dynamic memory management.

The function prototypes look like this:

In the first CBR function I use the pointer operator and in the second CBR function I use the reference operator.

I said that pointers are mainly used to send an array to a function but you can also use them with normal variables.

The complete functions:

Now let's see the output:

So we start with our variable wich has the value 5.
Inside the CBV-function we set it to 10.
But after the function output, we are back in the main function.
As I said, with CBV the variable doesn't change, because you are working with a COPY of it.

So the value of our variable is 5 again.

The variable has still the value of 5, so the output doesn't change if we send it to the first CBR-function.
Inside the CBR-function we change the value to 10.
Now the variable in the main function also changed to 10. This can be seen as we send the variable to the second CBR-function, because in the main function we are still working with the same variable.

The variable that we now send to the second CBR function has the value 10.
Inside there we change it to 11.
And because it's also CBR we changed the variable in the main function also to 11.

Sort:  

Thanks a lot bud always good to refresh up on c++ .It's been almost a year since i made a qt app now.Could you share which software you are using because i am curious and wanna start coding c++ again.

Thanks for your positive comment! :)
I'm using Eclipse as IDE and MinGW GCC as compiler.

http://www.eclipse.org/downloads/eclipse-packages/
http://www.mingw.org/

Coin Marketplace

STEEM 0.18
TRX 0.14
JST 0.030
BTC 58665.81
ETH 3153.57
USDT 1.00
SBD 2.44