How to Understand "Pass By Reference Within a Function" w3schools example? - c++

I'm having a hard time understanding how this example from the w3schools tutorial works.
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
system("pause");
return 0;
}
I think I understand the first part:
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
I'm basically referencing whatever x and y are going to be when I call the function. So x is going to be "pointing" to firstNum and y is going to be pointing to secondNum. It's going to do the switcheroo using a third variable as a placeholder.
However, after I call the function swapNums(firstNum, secondNum);, I don't understand how the function with its local variables has the ability to change the values of int firstNum = 10; and int secondNum = 20;.
My understanding is that variables within a function are "local" and the scope of said variables only extend within the function itself. How do the local variables change other variables outside their own function without any return statements?

Try this
#include <iostream>
void change_val_by_ref(int &x)
{
x=100
}
void change_val_by_val(int x)
{
x=50;
}
int main()
{
int whatever=0;
std::cout<<"Original value: "<<whatever<<"\n";
change_val_by_ref(whatever);
std::cout<<"After change by ref: "<<whatever<<"\n";
change_val_by_val(whatever);
std::cout<<"After change by val: "<<whatever<<"\n";
}
The output you will see is:
0
100
100
Let's see what happened
change_val_by_ref changed the original whatever, because the ref
was "pointing" to the VARIABLE.
change_val_by_val didn't change the whatever, because the argument of the function x has just copied the value of whatever, and anything that happens to x will not affect whatever, because they are not related.
That's the point of passing by ref.

Imagine you have banana and orange placed in two different plates. You place them into big box with a robotic hand.
You, obviously, can change their destination using you hand. But you want the robotic hand to do this task. You need to tell where the banana and orange are placed, so robotic hand can do its job. !Important robotic hand doesn't care about fruit, which is placed into these plates, it only cares about changing their positions.
By using a pointer, you just tell a function the placement of an object you want to change. And you can set your local, suitable name for this. So pointer is just the name of a plate, which contains a certain value.

References are syntactic sugar for passing around addresses of variables. Instead of the variable itself, you pass its memory address and then the function uses the address of the variable to change its value. Simple as that. Equivalent C code would be:
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}

Related

Calculates the position of the max element for array. function returns the max element. pass the array by the pointer and the pos. by the reference

i have a little problem with my college assignment. I don't really understand what's going on with pointers and reference. Could someone point me where I am making a mistake??
using namespace std;
int i, n, maax, *position;
void tablica()
{
int tab[n];
cout<<"enter data:"<<endl;
for (i=0; i<n; i++)
{
cin>>tab[i];
}
maax = tab[0];
for (i=0; i<n; i++)
{
if (maax<tab[i])
{
maax=tab[i];
*position=i+1;
}
}
}
int main()
{
cout<<"array size:"<<endl;
cin>>n;
tablica();
cout<<"max el. position is: "<<&position<<endl;
return 0;
}
Sure we can help you a little bit. But the whole topic of pointers and references cannot be covered in a short answer here on SO. You need to read a book.
The following will be very simplified and there is much more in reality. But let's start with this simple explanantion.
Let me give you a typical example that is often used in C or very early C++ books. Look at the function swap that should exchange the values of 2 variables.
#include <iostream>
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 1, b = 2;
swap(a, b);
std::cout << "a: " << a << "\tb: " << b << '\n';
}
We hope that after the call to the function swap, "a" will contain 2 and "b" will be 1. But it is not. Because in this case (and per default) the variables that are given to the function swap, are passed by value. So, the compiler will generate some code and copies the value of variables "a" and "b" into some local internal storage, also accessible with the name "a" and "b". So, the original "a" and "b" will never be touched or modified. By passing a variable by value, a copy will be mdae. This is often intended, but will not work in this example.
The next development stage was the pointer. The pointer is also a variable that contains a value. But this time it is the address of another variable somehwere in memory. If you have a variable like int a=3; then the 3 is somewhere stored in memory (decided by the compiler of the linker) and you can access the memory region with the name "a".
A pointer can store the memory address of this variable. So not the value 3 of the variable "a", but the address of the variable "a" in memory. The pointer points to that memory region, where the 3 ist stored. If you want to access this value, then you need to dereference the pointer with the * operator. And to get the address of variable 'a', you can write &a. But how does this help?
It helps you indirectly to get modified or result values out of a function. Example:
#include <iostream>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a = 1, b = 2;
swap(&a, &b);
std::cout << "a: " << a << "\tb: " << b << '\n';
}
In main we take the address of variable "a" and "b" and give this to the function. The address of the function (the pointer) will be given to the function as value now. A copy of the pointer will be made (not in reality) but this does not harm, because we can now modify the original values of the variable, by derefencing the pointer. Then the function ends and we will find the correct values in the original variables "a" and "b".
But, pointers are notoriously difficult to understand and very error prone. Therefore the "reference" has been invented. It is kind of an alias for a normal variable. And the good point is that if you pass a reference to the function, then you can modify immediately the original value. That makes things very convenient.
The function swap could then be written as
#include <iostream>
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 1, b = 2;
swap(a, b);
std::cout << "a: " << a << "\tb: " << b << '\n';
}
And this gives the intented result. And is by far simpler.
Now to your code. First, VLAs (variable length arrays), namely the int tab[n]; where 'n' is no compile time constant, are a not a ppart of the C++ language. You canot use them. You could and should use a std::vector instead, but you did not yet learn about it. So we will use new, to allocate some memory dynamically. Please note: In reality, new, raw pointers for owned memory and C-Style arrays should not be used. But anyway.
Then let us look at your requirements
function returns the max element. pass the array by the pointer and the pos. by the reference
So, we need a function to calculate the max element in an array, then return this value, and additionally copy the position of the max element in a variable, given to the function as reference. We will add an additional parameter for the size of the array, because we will not use VLAs here. The array will be given by pointer.
So the prototype of your function will be:
int getMaxElement(int *array, int sizeOfArray, int& positionOfMaxValue)
To implement such a function, we create an internal variable to hold the max value, which we will later return. Then, we compare all values in a loop against this max value and, if we find a bigger one, then we store this new result. As the initial value, we can simply take the first value of the array.
Example:
#include <iostream>
int getMaxElement(int* array, int sizeOfArray, int& positionOfMaxValue) {
int resultingMaxValue = 0;
if (sizeOfArray > 0) {
resultingMaxValue = array[0];
for (int i = 0; i < sizeOfArray; ++i) {
if (array[i] > resultingMaxValue) {
resultingMaxValue = array[i];
positionOfMaxValue = i;
}
}
}
return resultingMaxValue;
}
int main() {
// Get array size from user
std::cout << "\nPlease enter the array size: ";
int arraySize = 0;
std::cin >> arraySize;
// Create an array
int* array = new int[arraySize];
// Read all values into the array
for (int i = 0; i < arraySize; ++i)
std::cin >> array[i];
// Now calculate the max value and position of the max value
int position = 0;
int maxValue = getMaxElement(array, arraySize, position);
// Show result
std::cout << "\n\nResult:\nThe maximum value '" << maxValue << "' is at position " << position << '\n';
delete[] array;
}
Please remember: This is a very simplified explanation
You shouldn't use global variables (see Are global variables bad?). int tab[n]; is not standard C++, its a variable length array that is only available as extension on some compilers (see Why aren't variable-length arrays part of the C++ standard?). The segfault is because you never allocate memory for the position, it is initialized because its a global, but it doesnt point to an int (see Is dereferencing a pointer that's equal to nullptr undefined behavior by the standard?).
You do not need any array to get the max value and position. And there is no need to use a pointer in your code. Determine the maximum value and position in the same loop that is reading the input and return the result from the function instead of using the global variable:
#include <iostream>
int tablica(int n) {
std::cout<<"enter data:\n";
int max = 0;
int max_pos = 0;
std::cin >> max;
for (int i=1; i<n; i++) {
int number = 0;
std::cin>>number;
if (max<number) {
max=number;
max_pos = i;
}
}
return max_pos;
}
int main()
{
std::cout<<"input size:\n";
int n;
std::cin>>n;
int position = tablica(n);
std::cout<<"max el. position is: "<< position << "\n";
return 0;
}
Look at what the function should do:
"function returns the max element. pass the array by the pointer and the pos. by the reference"
It should not read any array elements.
It should not receive or return values in global variables.
It should not use a pointer to the position.
It should be passed an array (as a pointer) and somewhere to store the maximum position (as a reference), and return the maximum value.
That is, its prototype should look like
int tablica(const int* input, int size, int& max_position)
and main should look something like this:
int main()
{
int n = 0;
cout << "Array size: " << endl;
cin >> n;
int* data = new int[n];
for (int i = 0; i < n; i++)
{
cin >> data[i];
}
int position = -1;
int max_element = tablica(data, n, position);
cout << "The maximum element is " << max_element << ", at index " << position << endl;
delete [] data;
}
Implementing tablica left as an exercise.

Illegal hardware instruction on a c program compiled on Mac

I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int * x;
*x=10;
cout << fun(x);
return 0;
}
Pointers are just pointers. In your code there is no integer that you could assign a value to.
This
int * x;
Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:
*x=10;
You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? There is no int where x points to, because x doesnt point anywhere. Your code has undefined behavior. Output could be anything.
If you want to assign 10 to an int you need an int first. For example:
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int y = 0;
int * x = &y;
*x=10;
cout << fun(x);
return 0;
}
This assigns 10 to y. The cout is still printing the value of x, which is the adress of y. It does not print the value of y. Not sure what you actually wanted.
The problem is that in your program the pointer x is not pointing to any int variable. So first you have to make sure that the pointer x points to an int object as shown below.
You can sovle this as shown below:
int i = 0; //create the int object to which x will point
int *x = &i; //make x point to variable i
*x = 10; //dereference the pointer x and assign 10 to the underlying variable i
cout << *fun(x); //this prints 10

Passing Pointers By Reference vs Passing Pointers Into Functions

It's been a while since I've coded anything in C++. While I was trying to help another person as a CIS Tutor, he wanted to know why it's necessary to have an ampersand next to a pointer to an int.
I figured that if you were to pass a pointer by reference and you point to something else, the main knows after you passed that val will equal to whatever you set it equal to.
There will be an example below will demonstrate what I'm trying to say.
Is this correct?
//main function
int variable = 0;
int* val = &variable;
function1(val);
cout << *val << endl;
function2(val);
cout << *val << endl;
//Passing in a pointer with reference.
void function1(int*& value)
{
int variable = 9;
value = &variable;
}
//Passing in a pointer without reference.
void function2(int* val)
{
int variable = 9;
value = &variable;
}
My assumption is that the program will output 9 instead of 8 or 0. I hope this give you guys a clear picture of what I'm trying to ask.
The difference between passing the values and passing the reference is the same with pointers as with other values (actually pointers are nothing special they just hold numbers that sometimes are adresses of other objects).
With int:
void foo(int x) { x = 1; }
void bar(int& x) { x = 2; }
int main() {
int y = 5;
foo(y);
std::cout << y; // prints 5
bar(y);
std::cout << y; // prints 2
}
Now with pointers:
void foo(int* x) { x = 0; }
void bar(int*& x) { x = 0; }
int main() {
int y = 42;
int* z = &y;
foo(z);
std::cout << z; // prints the address of y
bar(z);
std::cout << z; // prints 0
}
Note that your function1 is broken, because when you call it
int* y;
function1(y);
std::cout << *y; // **baaam**
// the value y points to is already gone
the int inside the function ends its lifetime when the function returns and the caller cannot use the value in any meaningful way. Note that in this particular example you would probably get the "correct" value printed, but that is just by coincidence and dereferencing y after passing it to function1 is undefined behaviour.

Change the function signature

I'm new to C++ and for now there is one thing I would want to make clear. As I'm going through the tutorial,there is this program that stores user's input into an array and gives a sum of all numbers when the user exits the program:
//PROTOTYPE DECLARATION:
int readArray(int integerArray[], int maxNumElements);
int sumArray(int integerArray[], int numElements);
void displayArray(int integerArray[], int numElements);
int main(int nNumberofArgs, char* pszArgs[])
{
cout << "This program sums values entered\n";
cout << "Terminate the loop by entering a negative number" << endl;
//store the numbers from the user into a local array
int inputValues [128];
int numberOfValues = readArray(inputValues, 128);
//output the values and the sum of the values
displayArray(inputValues, numberOfValues);
cout << "The sum is " << sumArray(inputValues, numberOfValues) << endl;
return 0;
}
int readArray(int integerArray[], int maxNumElements)
{
int numberOfValues;
for(numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
{
//fetch another number
int integerValue;
cout << "Enter next number: ";
cin >> integerValue;
if (integerValue < 0)
{
break;
}
//otherwise store the number into the storage array
integerArray[numberOfValues] = integerValue;
}
//return the number of elements read
return numberOfValues;
}
//displayArray - display the members of an array:
void displayArray(int integerArray[], int numElements)
{
cout << "The value of the array is:" << endl;
for(int i = 0; i < numElements; i++)
{
cout << i << ":" << integerArray[i] << endl;
}
cout << endl;
}
//sumArray
int sumArray(int integerArray[], int numElements)
{
int accumulator = 0;
for(int i = 0; i < numElements; i++)
{
accumulator += integerArray[i];
}
return accumulator;
}
My questions are:
Is it neccessary to declare local variables in each function (e.g. int inputValues [128];)?
Would it be correct to store the input into the arguments that were declared in the function prototype? For example, can we just store everything into integerArray[] instead of creating a storage array integerValue ?
This may look obvious but I want to understand this to avoid making mistakes in the future.
inputValues is necessary if you want to pass an array to the function.
int inputValues [128];
int numberOfValues = readArray(inputValues, 128); //passing array to function
Either way you do it is fine. So what you have is not wrong.
As noted in the comments you could also pass inputValues by reference. Which you could declare the prototype of function like this.
int readArray(int (&integerArray)[128]);
Any changes you make to the array you passed by reference will be updated when the function returns to main because you are not operating on a copy of the array anymore.
Edit:
As #Kevin pointed out, you can use a template function to get the size of the array at compile time.
template<size_t N> int readArray(int (&integerArray)[N]);
There are a lot of understanding gaps in this question.
The function parameter lists will convert their input:
If the type is "array of T" or "array of unknown bound of T", it is replaced by the type "pointer to T"
Using the implicit array to pointer assignment:
Constructs a pointer to the first element of an array.
These two together hopefully help you to see that when you declare a function like: int readArray(int integerArray[], int maxNumElements), integerArray is really just a pointer to the first element of it's first argument. You call readArray(inputValues, 128) so the parameter integerArray is equivalent to &intputArray[0].
It is not necessary and you can use global variables instead but that is bad choice in terms security and visibility etc. This program can be done few different ways but I guess what you need to learn first is difference between local and global scope, pointer/array.
In the program, memory is allocated for
int inputValues[128]; //memory allocation
Then address of that location is passed here.
int numberOfValues = readArray(inputValues, 128);
It is much more efficient this way. But it will start make more sense once you get more experience with pointer and arrays.

C++ code malfunctioning

I wrote a basic linear search C++ code. Whenever I run this, the result I get is always the opposite of the expected result.
For instance, I want to search 4. In an array where it is present, it will say the number is not found, but upon searching an absent element, it will say the element is found at position 0.
Even after an hour or so of constantly looking at the code I have not found any solution.
#include <iostream>
using namespace std;
//scanning program
int linearsearch (int A[] , int z, int n, int srchElement) {
for (int z = 0; z < n; z++) {
if (A[z] == srchElement) {
return z;
}
}
return -1;
}
//main program
int main () {
int i, n, A[1000], z;
//asking for size of array
cout << "give size of the array needed to be scanned: ";
cin >> n;
cout << endl;
if (n > 999) {
cout << "invalid value";
return -1;
}
//making sure of the size of the array
cout << "enter " << n << " integers: ";
//asking for the array
for (i = 0; i < n; i++) {
cin >> A[i];
}
int srchElement, index;
do {
cout << endl << "enter element to search (-1 to exit ): ";
//srchElement is defined here
cin >> srchElement;
if (srchElement == -1) break;
index = linearsearch(A, n, srchElement, z);
//calling thscanning function
if (index == -1) {
cout << srchElement << " not present" << endl;
}
//outputting the results of the scan
else {
cout << srchElement << " present " << index << endl;
}
} while (true);
return 0;
}
Your parameters to linearsearch are not in the correct order - you are passing n into the unused z parameter. With your current function you should call it like:
index=linearsearch(A, 8675309, n, srchElement);
I recommend you get rid of z as a parameter, then you won't need to pass a value to it.
Also please note: Spaces and indentation do not make your program run slower, but they do make it a lot easier to read.
The order of arguments in the function definition is not the same as in the function call.
It should be like (Line no 4):
int linearsearch (int A[] , int n, int srchElement, int z)
This is your search function correctly formatted:
int linearsearch (int A[] , int z, int n, int srchElement)
{
for (int z = 0; z < n; z++)
{
if(A[z] == srchElement)
{return z;}
}
return -1;
}
and here is how you call it:
index=linearsearch(A, n, srchElement, z);
You pass a value z in with the call. It is unitialised and does nothing, in main() or in the function.
You pass the arguments into the function in the wrong order. You are:
passing n (from main()) into the unused z value
searching for the uninitialised z (from main())
passing in the element you are looking for as n (array size). (This will quite likely result in out of bounds error, e.g. if searching for -1)
Try this:
int linearsearch (int A[], int n, int srchElement)
{
for (int z = 0; z < n; z++)
{
if(A[z] == srchElement)
{return z;}
}
return -1;
}
and here is how you call it:
index=linearsearch(A, n, srchElement);
You immediate problem: as The Dark spotted, this call:
index=linearsearch(A, n, srchElement, z);
doesn't match the declaration
int linearsearch (int A[] , int z, int n, int srchElement)
Function arguments in C++ are positional: just because the last call argument and the second declaration parameter are both called z doesn't mean anything.
Now, there are several local issues of style:
this kind of function is risky in the first place
int linearsearch (int[],int,int,int)
because it relies on you remembering the correct order for the last three integer parameters. If you must do this, you should be extra careful to give them all distinctive names, be very clear about which is which, and keep the order consistent across families of functions.
It's better, where possible, to help the compiler help you out, by either giving the arguments distinct types (or enumerations, or whatever), or grouping them into a structure.
For example, using a std::vector<int> instead of your array effectively groups int A[] and int n together in an object, so they can't get out of sync and n can't get confused with the other integers floating around
You shouldn't be passing z in the first place. You immediately hide it with a local int z in the loop, so it can't be doing anything. Remove it from both the declaration and the call. This simplification is sufficient to fix your bug.
Your secondary problem is that the code is ugly. It's poorly formatted and hard to read, and and that makes it more difficult to spot mistakes. Try to make your code simple and readable: there's less opportunity for things to go wrong, and its easier to see the problems when they occur.
Your tertiary problem is that the code is bad. Most of this can be done using standard library facilities (making your code simpler), which are themselves well-tested and generally have carefully-designed interfaces. Use them first, and replace if necessary.