summaryrefslogtreecommitdiff
path: root/CPP/Basics/functions.cpp
blob: 5a269926e26ba9a3d357151e339be46bc1d63cf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>

// C++ can pass arguments are references

// by value
int square(int x)
{
	return x * x;
}

// swap by value (passing pointers)
void swap(int *x, int *y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}

// Swap by reference - function overload
void swap(int& x, int& y)
{
	int temp = x;
	x = y;
	y = temp;
}


int main(void) {

	int a = 9, b;
	b = square(a);
	std::cout << "Square of a: " << b << std::endl;
	std::cout << "A: " << a << " B: " << b << std::endl;
	swap(&a, &b);
	std::cout << "Swapping by addr value:" << std::endl;
	std::cout << "New A: " << a << " New B: " << b << std::endl;
	swap(a, b);
	std::cout << "Swapping by reference:" << std::endl;
	std::cout << "New A: " << a << " New B: " << b << std::endl;
	return 0;
}