Functions, Passing by Address

void swap(int x, int y){
	int temp = x;
	x = y;
	y = temp;
}

int main(){
	int x = 10, y = 5;
	cout << "Before: x = " << x <<", y = " << y << endl;
	swap(x,y);
	cout << "After: x = " << x <<", y = " << y << endl;
}
void swap(int*x, int*y){
	int temp = *x;
	*x = *y;
	*y = temp;
}

int main(){
	int x = 10, y = 5;
	cout << "Before: x = " << x <<", y = " << y << endl;
	swap(&x,&y);
	cout << "After: x = " << x <<", y = " << y << endl;
}

Pass by Reference

void swap(int&x, int&y){
	int temp = x;
	x = y;
	y = temp;
}

int main(){
	int x = 10, y = 5;
	cout << "Before: x = " << x <<", y = " << y << endl;
	swap(x,y);
	cout << "After: x = " << x <<", y = " << y << endl;
}
int a = 7, b = 12;
int& ra = a;   // ra now refers to a, whose value is 7
ra = b   // this doesn't do any reassigning, you just made ra = a = b = 12
int x = 10;
int &y = x;
y = 20;
  1. x = 20, y = 20
  2. x = 20, y = 10
  3. x = 10, y = 20

Compiling Single Files

#include <iostream>
using namespace std;

void printNum(int x){
	cout << "The value is " << x << endl;
}

int userInputNum(){
	int x;
	cout << "Enter an integer " << endl;
	cin >> x;
	return x;
}

int main(){
	int num = userInputNum();
	printNum(num);
	cin >> num;
}