L03 Functions and Passing Paramaters
Function prototype: the return type of the function, plus the function name and input arguments
function that calculates the factorial of a number
// c++ program that calculates the factorial of a number
#include <iostream>
using namespace std;
int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main(void) {
int num = 4;
cout << "num: " << num << ", factorial value: " << factorial(num) << endl;
return 0;
}
Just like in C, variables in functions are not stored in global memory
so you must pass the value of a variable to the function
Also just like in C, after the function finishes running, any variables vanish from memory
Pass-by-value: the arguments that you pass into a function when calling it.
swapping two variables locally within a function
// function that swaps two variables, but only in the function, not in main
#include <iostream>
using namespace std;
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
cout << "swapped values: x = " << x << ", y = " << y << endl;
}
int main(void) {
int x = 7, y = 13;
swap(x,y);
return 0;
}
pointers
same as in C; variable that holds the location (address in memory) of another variable.
- uses data type
int* - when creating a pointer, you can use
&pointer_nameto get the address *pointer_nameis dereferences the pointer, which returns the value at that address
e.g.px = &x;creates pointer pointing to address of variable x
pass-by-pointers
pass addresses of variables to functions so that they can affect variables globally.
function that swaps the values of variables globally
#include <iostream>
using namespace std;
void swap(int* px, int* py) {
int temp = *px;
*px = *py;
*py = temp;
}
int main(void) {
int x = 7, y = 13;
swap (&x, &y);
cout << "swapped: x = " << x << ", y = " << y << endl;
}
pass-by-reference
Pass-by-reference will make the same program less complex!
A reference is an alias, an alternate name, to a variable
int a = 7;
int &ra = a; (reference to an integer a)
- Does NOT create any special space in memory, it's JUST a reference, same location as the variable it's referencing.
- Also, pass-by-references cannot be reassigned!
- References must be initialized at the time of declaration.
So, we can rewrite the [[#function that swaps the values of variables globally]] so that it's nicer to read.
#include <iostream>
using namespace std;
void swap(int& rx, int& ry) { // something is wrong here i need to debug
int& temp = rx; // reference to x
rx = ry;
ry = temp;
}
int main(void) {
int x = 7, y = 13;
int& rx = x, ry = y;
swap (rx, ry);
cout << "swapped: x = " << x << ", y = " << y << endl;
}