Pass by reference in c++



#include <iostream>
using namespace std;
void f(int& r) {
cout << "r = " << r << endl;
cout << "&r = " << &r << endl;
r = 5;
cout << "r = " << r << endl;
}
int main() {
int x = 47;
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
f(x); // Looks like pass-by-value,
// is actually pass by reference
cout << "x = " << x << endl;
}
Suggest your opinion about this pass by reference in c++.

Comments

  1. int& a = b is setting a's ADDRESS to b's ADDRESS (a is a reference to b)

    ReplyDelete
  2. @above i wanted to know in this method whether there is any extra storage created for r.

    ReplyDelete
  3. int& create a alias...so no storage is created...but whatever change we do in the alias it will be reflected back to ots main variable....

    ReplyDelete

Post a Comment

Popular posts from this blog