1 / 6

Understanding C++ Call by Value and Call by Reference

This guide explores key concepts in C++ related to function argument passing, specifically call by value, call by reference, and call by pointer. It demonstrates how these methods influence the way variables are accessed and modified in memory. Through examples, we will illustrate how data is passed to functions in C++, highlighting the differences between the methods using strings and integers. This comprehensive overview will improve your understanding of memory management and variable references in C++. Perfect for beginners looking to deepen their programming skills.

gagan
Télécharger la présentation

Understanding C++ Call by Value and Call by Reference

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Examples

  2. float x = 10.7; float& rx = x; cout<<x<< endl; //output: 10.7 cout<<&x<<endl; //address of x in memory cout<<rx<< endl; // output: 10.7 cout<<&rx<< endl; //address of in memory = &x --rx; // equivalent to --x;

  3. inti,*j; i=5; cout<<“------------------------------" <<endl; cout<<i<<endl; //output: 5 cout<<&i<<endl; //output: i address in memory j=&i; cout<<j<<endl; //output: i address in memory cout<<“---------------------------------" <<endl;

  4. #include <iostream> using namespace std; int count(int x); int main() { int x=3; cout<<"value of count(x)= "; cout<<count(x)<<endl; return 0; } int count (int x) { if (x==0) return 0; else { cout<<x; return count(x-1); } }

  5. #include <iostream> using namespace std; int count(int x); int main() { int x=3; cout<<"value of count(x)= "; cout<<count(x)<<endl; return 0; } int count (int x) { int y; if (x==0) return 0; else { y = count(x-1); cout<<x; return y; } }

  6. #include <iostream> #include <string> using namespace std; void call_by_v(string); //call by value void call_by_rr(string &); //call by reference using reference void call_by_rp(string *); //call by reference using pointer int main() { string s = "Welcome"; call_by_v(s); cout<<s<<endl; call_by_rr(s); cout<<s<<endl; call_by_rp(&s); cout<<s<<endl; return 0; } void call_by_v(string a) { a=" s will not changed"; } void call_by_rr(string & a) { a="s will change using reference"; } void call_by_rp(string *a) { *a="s will change using pointers"; }

More Related