ch3-Function call (by value or reference)

Chapter_3     Exercise_3-6 Exercise_3-7







CONTENTS:     PassByValue.cpp     PassAddress.cpp     PassReference.cpp




PassByValue.cpp     TCP1, p. 149-150         download


#include <iostream>
using std::cout;
using std::endl;

void f(int a);

int main()
{
int x = 47;
cout << "x = " << x << endl; // 47
f(x); // pass `x' by value
cout << "x = " << x << endl; // 47

return 0;
}

void f(int a)
{
cout << "a = " << a << endl;
a = 5;
cout << "a = " << a << endl;
}
/*
g++ PassByValue.cpp -o PassByValue
./PassByValue
x = 47
a = 47
a = 5
x = 47
*/





Note:  See also ch1-args on the blog Kernighan_and_Ritchie, Chapter_1, Sec. 1.8.











PassAddress.cpp     TCP1, p. 150-151         download


#include <iostream>
using std::cout;
using std::endl;

void f(int* p);

int main()
{
int x = 47;
cout << "x = " << x << endl; // value of `x'
cout << "&x = " << &x << endl; // address of `x'
f(&x); // &x is a pointer to x (passed by reference)
cout << "x = " << x << endl; // value changed
cout << "&x = " << &x << endl; // address did not change

return 0;
}

void f(int* p)
{
cout << "p = " << p << endl; // address (value of p)
cout << "*p = " << *p << endl; // underlying value
*p = 5; // modify the underlying value that `p' point to
cout << "p = " << p << endl; // address does not change
cout << "*p = " << *p << endl; // underlying value changes
}
/*
g++ PassAddress.cpp -o PassAddress
./PassAddress
x = 47
&x = 0x7ffd1f270084
p = 0x7ffd1f270084
*p = 47
p = 0x7ffd1f270084
*p = 5
x = 5
&x = 0x7ffd1f270084
*/











PassReference.cpp     TCP1, p. 152-153         download


#include <iostream>
using std::cout;
using std::endl;

void f(int& r); // only in C++, does not work in C

int main()
{
int x = 47;
cout << "x = " << x << endl; // value
cout << "&x = " << &x << endl; // address
f(x); // Looks like pass-by-value, is actually pass by reference
cout << "x = " << x << endl; // value changed
cout << "&x = " << &x << endl; // address did not change

return 0;
}

void f(int& r)
{
cout << "r = " << r << endl; // value
cout << "&r = " << &r << endl; // address
r = 5; // value changes
cout << "r = " << r << endl;
cout << "&r = " << &r << endl; // address remains the same
}
/*
g++ PassReference.cpp -o PassReference
./PassReference
x = 47
&x = 0x7ffe4ad4bab4
r = 47
&r = 0x7ffe4ad4bab4
r = 5
&r = 0x7ffe4ad4bab4
x = 5
&x = 0x7ffe4ad4bab4
*/









Chapter_3     Exercise_3-6 BACK_TO_TOP Exercise_3-7



Comments

Popular posts from this blog

Contents