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 ?
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.
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?