Passing by reference

0 Ritvik Raj · May 15, 2015
Will someone please explain me how this C++ code works: (I'm not clear what is happening during the passing step)

#include<iostream>
using namespace std;

void changeX (int &x){
    x = 15;
}



int main()
{
    int x = 10;
    changeX(x);
    cout << x;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Sengngy Kouch · May 15, 2015
So the problem is that when I use < < ... it will ignore other part of my code. Please use this one. Sorry to post so many times.


int main()
{
int a = 10;

//Here you just pass a copy of your "a". so after you finish your function call. a is still 10.
changeByValue(a); //function called here.
cout << a; //a will = 10. Because your real "A" is never touched.

//Here you pass your real "A" to the function.
changeByRef(a);
cout << a; // a will = 15. Because you pass your real "A" to the function.

}
0 Sengngy Kouch · May 15, 2015
This really bugs me. some how this website mess up my layout and format. Please use the main Function from here : 


int main()
{
int a = 10;

//Here you just pass a copy of your "a". so after you finish your function call. a is still 10.
changeByValue(a); //function called here.
cout
0 Sengngy Kouch · May 15, 2015
Hi there! 

Please ignored my first post. Some how it mess up my format. Please read this one instead.



#include
using namespace std;


//Pass by Reference. Pass the address or the real x to your function.
void changeByRef (int &x){
x = 15;
}


//Pass by Value. Pass a copy of your x to the function.
void changeByValue ( int x)
{
x = 15;
}



int main()
{
int a = 10;

//Here you just pass a copy of your "a". so after you finish your function call. a is still 10.
changeByValue(a); //function called here.
cout
0 Sengngy Kouch · May 15, 2015


#include
using namespace std;


//Pass by Reference. Pass the address or the real x to your function.
void changeByRef (int &x){
x = 15;
}


//Pass by Value. Pass a copy of your x to the function.
void changeByValue ( int x)
{
x = 15;
}



int main()
{
int a = 10;

//Here you just pass a copy of your "a". so after you finish your function call. a is still 10.
changeByValue(a); //function called here.
cout
NOTE: if you

cout<< changeByValue(a); // you might print out a = 15, but if you...... cout<<a; again, you will notice that a = 10 now. This is because you only pass a copy of you 'a" to the function. The real 'a" is never touch.



I hope this help.
  • 1

C++

107,075 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator