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
- Something new in C++ that lets functions see and operate memory without using address
- Syntax for defining a reference:
int&x or int& x or int &x.
- A C++ reference uses less memory than a C pointer since you don’t have to store the address being pointed to
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
- You cannot reassign a reference. You must initialize them at declaration. Reassigning a reference will change the value at that location in memory.
int x = 10;
int &y = x;
y = 20;
- x = 20, y = 20
- x = 20, y = 10
- 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;
}
- To compile this file using g++, use the compiler + source code name + output .exe name as such:
g++ main.cpp -o main
- To run this file, you type
./main
g++ -c main.cpp → this is the compiler giving us main.o, a binary object file
g++ main.o -o main → this is the linker linking the object file to an executable