Array element passing to function parameter

Have a question on array elements passing to function argument. I read the book and I don't get the fact on how it says the array element is passed by value. So my question is that I know here that the function call showValue(numbers[index]); is being called 8 times, so is the element being passed to the function parameter num or is the element being passed by value of the function parameter num? In the book says the following:

"The showValue function simply displays the contents of num and doesn’t work directly with the array element itself. (In other words, the array element is passed by value.)"

To my guess of what the book says, which that the function showValue parameter num displays only the value and not the element it self, because it says the array element is passed by value.

Here is the code, thank you very much:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

void showValue(int); 

int main()
{
	const int SIZE = 8;
	int numbers[SIZE] = { 5, 10, 15, 20, 25, 30, 35, 40 };

	for (int index = 0; index < SIZE; index++) 
	{
		showValue(numbers[index]);
	}

	system("pause");
}

void showValue(int num)
{
	cout << num << " ";
}
Last edited on
closed account (SECMoG1T)
passing by value : means a copy of a variable is used instead of the original variable such
that any changes that occur to that copy would not be reflected in the
original variable... whether the variable is an array element, a vector a
double or any type.

passing by reference: means the original variable is passed to the function, any change to
that variable will be retained even after the function exits;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

///this functions adds 2 to a variable
int add_by_val(int var)///by value
{
    var += 2;
    std::cout<<"by value: "<<var<<"\n";
}

int add_by_ref(int& var)//by reference
{
    var += 2;
    std::cout<<"\nby ref  : "<<var<<"\n";
}

int main()
{
    int y = 2;

    add_by_val(y);
    ///the original value of variable y is unaffected by the function call
    /// because a copy of y was used
    std::cout<<"value of y after fn call: "<<y<<"\n";

    add_by_ref(y);
    ///the  value of variable y now reflects the changes after the function call
    /// because the original variable y was passed to the fn().
    std::cout<<"value of y after fn call: "<<y<<"\n";

}


hope you get the idea.
Last edited on
Thank you, that helped!
Topic archived. No new replies allowed.