-3

What does a and b hold in function swapp ? are they holding value or address ? what kinda variables are they I am lost here !

#include <iostream>
using namespace std;
template <class T1 = int>
void swapp(T1 &a, T1 &b)
{
    T1 temp;
    temp = a;
    a = b;
    b = temp;
}
int main()
{
    int x = 5, y = 10;
    swapp(x, y);
    cout << x << " " << y;
    return 0;
}
YashRM
  • 1
  • 4
  • 1
    These arguments are passed as references though. – Quimby Jul 17 '21 at 15:25
  • I really don't get it what a and b holds ? are they holding value or address ? I am confused – YashRM Jul 17 '21 at 15:26
  • 1
    'a' and 'b' are references. From the point of view of the language, they are just aliases to some other variables. "value" vs "address" vs "whatever" is an implementation detail. –  Jul 17 '21 at 15:27
  • They represent the object by a name, they are the same as any other variable, expect they did not create the object and its lifetime is not tied to them. When you write the expression `x` for `int x;` its type is also a reference to int. – Quimby Jul 17 '21 at 15:28
  • Okay I get it that they are alias but they how come they change the value of original variables x and y ? (sorry if I am asking stupid question here but I am really confused) – YashRM Jul 17 '21 at 15:29
  • Because they *reference* the same object. It's not a stupid question, but you are not the first to ask it, see e.g. [this](https://isocpp.org/wiki/faq/references#overview-refs). – Quimby Jul 17 '21 at 15:30
  • 2
    Using a reference is indistinguishable from using the variable being referred to. That's all there is to it. The reference doesn't even really "exist" as far as the language is concerned. –  Jul 17 '21 at 15:30
  • thanks I will check the document this really helps – YashRM Jul 17 '21 at 15:31
  • If you know Unix, think of references as hardlinks to inodes, except the lifetime of the object is tied to the hardlink which created the node. – Quimby Jul 17 '21 at 15:32
  • 2
    okay it was simple it's like giving function swapp permission to access x and y but with alias names a and b ! – YashRM Jul 17 '21 at 15:33
  • You could use `std::swap` instead of wasting your time writing *and debugging* your own function. – Thomas Matthews Jul 17 '21 at 18:45

2 Answers2

0

when you are using objects as parameter of a function you have to use "&" if you are trying to change their property. if you don't put the "&" before the name of the object, the function will not act on the object itself but on a copy of the object, which means that it won't swap. here if it helps : https://isocpp.org/wiki/faq/references

Bryz
  • 61
  • 3
0

What does a and b hold in function swapp ?

a and b refer to the objects that were passed as arguments.

are they holding value

No.

or address ?

This is a reasonable way to think about it.

what kinda variables are they

They are references.

eerorika
  • 232,697
  • 12
  • 197
  • 326