APS105 L10 - Functions

#APS105 Slides Lecture Link to web notes
Just as how int main(void) {} is a function, we can create our own functions using similar syntax.

#include <stdio.h>
int addTwo(int x) {
	x += 2;
	return x;
}

int main(void) {
	printf("14 + 2 is %d", addTwo(14)); 
}
Important! You must always declare the function before main.

Either declare the function and its contents before main, or simply declare the function and specify its contents after main.

Example: Print a mirrored triangle of stars.

#include <stdio.h>

void printSpaces(int spaces, int maxRows) {
	for (int space = 1; space < maxRows - spaces; ++space) {
		printf(".");
	}
}

int main(void) {
	int maxRows = 5;
	for (int row = 0; row < maxRows; ++row) {
		printSpaces(row, maxRows);
		for (int col = 0; col <= row; ++col) {
			printf("a");
		}
		printf("\n");
	}
	return 0;
}

If your function doesn't actually return anything, use void functionName() {} to signal to C that it shouldn't expect any return statement from the function.

Also, variables declared inside functions are not global. Thus, if a variable x is declared both inside main and functionName, any references to x in main will only use the value declared inside of main.
Similarly, you won't be able to access the value of x declared inside of main, unless you pass it through the function's arguments.

Anything defined within a function is called an "argument"

This means that arguments are local, assuming that is even the right terminology.


Pass By Value

Pass by values in a function in C are values that are fed into the function upon each instance of it being called. void in int main(void), for instance, is a pass by value.

Example: Pass By Value

#include <stdio.h>

void functionName(int passByValue) {
	passByValue *= 2;
	printf("inside of the function, we change the pass by value to: %d\n", passByValue);
}

int main(void) {
	int x = 1;
	functionName(x);
	printf("however, the value outside the function is still: %d\n", x);
	return 0;
}