Skip to content

Instantly share code, notes, and snippets.

@jg75
Created April 17, 2019 14:51
Show Gist options
  • Save jg75/211e7a3ef665b38643a976c2345f3230 to your computer and use it in GitHub Desktop.
Save jg75/211e7a3ef665b38643a976c2345f3230 to your computer and use it in GitHub Desktop.
pass by reference vs pass by value
#include <iostream>
using namespace std;
struct record_t
{
int id;
};
void Mutable(record_t &record);
void Immutable(record_t record);
int main()
{
record_t record;
record.id = 0;
record_t *ptr = &record;
cout << "Record" << endl;
cout << "Before Mutable: " << &record << ' ' << record.id << endl;
Mutable(record);
cout << "After Mutable: " << &record << ' ' << record.id << endl;
cout << endl;
cout << "Before Immutable: " << &record << ' ' << record.id << endl;
Immutable(record);
cout << "After Immutable: " << &record << ' ' << record.id << endl;
cout << endl;
ptr->id = 0;
cout << "Pointer" << endl;
cout << "Before Mutable: "
<< ptr << ' ' << ptr->id << ' '
<< &record << ' ' << record.id << endl;
Mutable(*ptr);
cout << "After Mutable: " << ptr << ' ' << ptr->id << ' '
<< &record << ' ' << record.id << endl;
cout << endl;
cout << "Before Immutable: " << ptr << ' ' << ptr->id << ' '
<< &record << ' ' << record.id << endl;
Immutable(*ptr);
cout << "After Immutable: " << ptr << ' ' << ptr->id << ' '
<< &record << ' ' << record.id << endl;
cout << endl;
cout << "Address of record: " << ptr << endl;
cout << "Address of pointer: " << &ptr << endl;
return 0;
}
void Mutable(record_t &record)
{
record.id = 1;
cout << "Inside Mutable: " << &record << ' ' << record.id << endl;
}
void Immutable(record_t record)
{
record.id = 2;
cout << "Inside Immutable: " << &record << ' ' << record.id << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment