pass by reference

May 22, 2012 at 3:02pm
Some one please tell me the real difference between pass by value and pass by reference.
I mean , the problem is why some programmes wont work if it is not pass by reference
eg:
#include <iostream>
using namespace std;
int main()
{
void intfrac(float, float&, float&);
float number, intpart, fracpart;
do {
cout << “\nEnter a real number: “;
cin >> number;
intfrac(number, intpart, fracpart);
cout << “Integer part is “ << intpart
<< “, fraction part is “ << fracpart << endl;
} while( number != 0.0 );
return 0;
}

void intfrac(float n, float& intp, float& fracp)
{
long temp = static_cast<long>(n);
intp = static_cast<float>(temp);
fracp = n - intp;
}


IF I REMOVE THE "&" MARK , THEN THE RPOGRAMME WILL NOT WORK. ACTUALLY I THOUGHT PASS BY REFERENCE IS JUST ONLY ANOTHER WAY TO SAVE MEMORY AND ACCESS THE DATA , WITHOUT GETTING COPIES OF IT .. .. THEN WHY THE PROGRAMME IS NOT WORKING ?
May 22, 2012 at 3:22pm
Pass-by-value passes a COPY of the data. Then, that COPY is what gets worked on. Changes are made to the COPY. When the function ends, the COPY is destroyed. What happened to the original? Nothing. It did not get changed.
May 22, 2012 at 3:28pm
ya ya , its true . But why the programme is not working when the "&" is removed .. ?
May 22, 2012 at 3:35pm
I find it hard to believe that you can say you understand but also not know why removing the & means it doesn't work.

Okay, even simpler.

When the & is removed, intpart and fracpart in the main function do NOT get changed by the function intfrac. Is that clear? They DON'T change. Do you understand that?
May 22, 2012 at 3:48pm
damn it , got it , .. I cant beleive y I was so blind not to understand .. anyway .. Thanks ..!!!!!!!!
Topic archived. No new replies allowed.