Thursday, 21 September 2017

Returning pointer from function in C++

/*
 Demo of returning pointer from function in C++
*/
#include "iostream"
using namespace std;

int globalN = 20;


int *returnPointerFromFun(){

 return &globalN;
}


int main(){
 int localN=30;
 int *ptr;
 ptr = &localN;
 cout<<"printing local value: "<<*ptr;
 ptr = returnPointerFromFun();
 cout<<endl<<"printing global value: "<<*ptr<<endl;
 return 0;
}
/*
 OUTPUT
[pavan@localhost Pointers]$ g++ ReturningPointer.cpp
[pavan@localhost Pointers]$ ./a.out 
printing local value: 30
printing global value: 20
[pavan@localhost Pointers]$ 

*/

No comments: