Passing by value

Hello! The output of this program is 5 and 125. But if I write only "cubeByValue( number )" i.e just call the function on 9th line, then output is 5 and 5. Why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
using namespace std;
int cubeByValue( int ); // prototype
int main()
 { 
    int number = 5;

   cout << "The original value of number is " << number;
   number = cubeByValue( number ); // pass number by value to cubeByValue
  // calculate and return cube of integer argument
   cout << "\nThe new value of number is " << number << endl;
 } // end main
 
int cubeByValue( int n )
{
   return n * n * n;
    // cube local variable n and return result
}
Last edited on
But if i store the (n*n*n) in n {line 16} i.e
n= n * n * n;...then the output is 5 and 125. Why is that?
Passing by value means that the value sent to the function via the function call will NOT be changed. This is because the function makes its own copy of the variable using a local variable.

So if you had a function
int cubeByValue( int n )
What it really is saying is that whatever is sent through the function call would be stored in a new local variable called 'n' with type 'int'.

1
2
3
4
int cubeByValue( int n )
{
   return n * n * n;
}

gets interpreted as
1
2
3
4
5
6
int cubeByValue( value sent to function )
{
   int n = value sent to function;
   return n * n * n;
    // cube local variable n and return result
}


Notice that the return value gives n*n*n, our result. So when we assign the return of the function to number, number would hold n*n*n which in our case was 125.

But when you didn't assign the return value of the function to number, number remains unchanged. Because remember the function doesn't change the value that is passed to it.

But what if I want the value sent to the function to be changed?
That is achieved using passing by 'reference'

Try this:
1
2
3
4
5
int cubeByValue( int& n )
{
   n = n * n * n;
    // no local variable made
}


And you will notice that it returns 5 and 125.
Last edited on
So the conclusion is that even if I am passing by value, I can get the updated result from the function by doing this
number =cubeByValue( number ); which means that I am storing the returned result in the respected variable.
And cubeByValue( number ); is just function calling and providing function the value. The function makes a new variable, do the respected modifications and stores the result in it and returns this value to the main function. Now it becomes necessary to assign the result to the actual variable to see the changes!
Am I right?
Yes precisely. You can see why passing by address would be better here because it avoids unnecessary copying of data. So when you're passing larger arguments like big vectors then it becomes essential to pass by address.
Bundle of Thanks! Stay blessed!
Topic archived. No new replies allowed.