c++ pass by reference code example
Example 1: how to pass a string by reference in c++
#include <iostream>
using namespace std;
void func (string &s)
{
s+="d";
}
int main()
{
string a="abc";
func(a);
cout << a << endl;
return 0;
}
Example 2: passing reference in c++
#include <iostream>
using namespace std;
struct demo
{
int a;
};
int main()
{
int x = 5;
int y = 6;
demo d;
int *p;
p = &x;
p = &y;
int &r = x;
r = y;
p = NULL;
p++;
r++;
cout << &p << " " << &x << endl;
cout << &r << " " << &x << endl;
demo *q = &d;
demo &qq = d;
q->a = 8;
qq.a = 8;
cout << p << endl;
cout << r << endl;
return 0;
}
Example 3: pass by value and pass by reference c++
#include <iostream>
using namespace std;
void by_value(int x) {
x *= 2;
}
void by_reference(int &x) {
x *= 2;
}
int main() {
int a1 = 5, a2 = 5;
cout << "Before: a1 = " << a1 << ", a2 = " << a2 << "\n";
by_value(a1);
by_reference(a2);
cout << "After: a1 = " << a1 << ", a2 = " << a2 << "\n";
return 0;
}