c++ - Returning by reference -


sorry if question basic.

program 1:

#include <iostream> using namespace std;  int   max(int &a) {    +=100;    return a; }  int main ( int argc, char ** argv) {    int x=20;   int y;   y = max(x);   cout <<"x , y value  "<<x<<"and"<<y<<endl;  } 

output:

x, y value 120and120

program 2:

#include <iostream> using namespace std;  int & max(int &a) {    +=100;    return a; }  int main ( int argc, char ** argv) {    int x=20;   int y;   y = max(x);   cout <<"x , y value  "<<x<<"and"<<y<<endl;  } 

output:

x, y value 120and120

the difference between program1 , program2 second program returns reference. difference?

program1: copies referenced variable when returning that,
program2: returns reference referenced variable (the same reference, actually?).

there no difference in output since value copied variable 'y' either way.

however, program1 performs one more copy operation program2.

problem happens when like:

int&  max(int a) //  value variable {    +=100;    int &a1 =    return a1;  // returning reference  local  } 

here in version of max() variable a scope local max() , if return reference a. stack-allocated go away , referring nothing. wrong!

read more explanation here


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -