+ 4

Do Reference Variables Means That You Create A Mirror Copy Of That Particular Value.

1).IS IT TRUE THAT ANY CHANGE MADE IN OUR VARIABLE GETS COPIED TO REFERENCE VARIABLE TOO. 2).CAN YOU PLS. EXPLAIN ME WHY THEY HAVE USED BOTH * AND & IN SWAP FUNCTION.THANKS #include<iostream> using namespace std; void swap(char * &str1, char * &str2) {   char *temp = str1;   str1 = str2;  str2 = temp; } int main() {   char *str1 = "GEEKS";  char *str2 = "FOR GEEKS";  swap(str1, str2);   cout<<"str1 is "<<str1<<endl;  cout<<"str2 is "<<str2<<endl;  return 0; }

7th Apr 2018, 6:06 PM
™TheChamp921
™TheChamp921 - avatar
4 Respostas
+ 4
Reference variables means the address of the original is passed into the function. Therefore, the compiler uses an instruction to load that address and a second to reference the original data. String or arrays of char are dealt with via a reference so str1 has the address of the string as it's value. That is what your char * states. What your code does is use two instruction to get the address stored in the original str1 and copy it to temp. It then updates str1 to point to the string the original str2 points to. Finally, it changes the original str2 to point to the string temp is holding on to.
7th Apr 2018, 6:23 PM
John Wells
John Wells - avatar
+ 4
Umm..Thanks!! Grandpa But All This is a Bit More Technical for me. Can You Explain It More Clearly, Help Appreciated!😊
7th Apr 2018, 6:29 PM
™TheChamp921
™TheChamp921 - avatar
+ 4
That's What I Needed.Thanks Grandpa😊 Best wishes!!
7th Apr 2018, 6:43 PM
™TheChamp921
™TheChamp921 - avatar
+ 2
You write your message on a piece of paper and you put that paper into an envelope. You give that envelope to your friend str1. You do the same with the second handing it to str2. You also have a rule that they can't touch 2 envelopes at once so you grab a third friend temp. You ask temp to hold the envelope str1 is holding so they can take str2's envelope. Then str2 is free to take the envelope temp is holding. After which, the str friends can open their envelope and read their messages.
7th Apr 2018, 6:41 PM
John Wells
John Wells - avatar