Hi! C++ programmers! I have questions about references and that questions are:
When should I use them?
What is the reason to use a reference?
I know that I should use a reference whenever possible instead of using a pointer.
I understand the syntax of references but not why I should use them? And what's the reason to use a reference?
I had a code in the book that I read that look like this as an example of a function with parameter references
Code:
#include <iostream>
using namespace std;
void badSwap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
void goodSwap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
int arg1 = 12;
int arg2 = 22;
badSwap(arg1, arg2);
cout << "badSwap(): " << "X: " << arg1 << " Y: " << arg2 << endl;
goodSwap(arg1, arg2);
cout << "goodSwap(): " << "X: " << arg1 << " Y: " << arg2 << endl;
return 0;
}
So I have a function called badSwap() which outputs the lowest score first and the highest last. And the function takes two arguments that is two int variables.
And I have a function called goodSwap() that takes two int references as arguments. I have exactly same code in their function body but their behaviors are diffrent from each other?
I don't understand why them are diffrent? One of them returns the value 12, 22 and the other one 22, 12??
Why is that? Shouldn't the functions do the same thing? I need to know why them behave like that I didn't really understand why even if I read that pages many times.
And I'm wondering when should I use references and why are they efficient?