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));
}
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.
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.
- Whenever a pass by value is fed into a function, a copy of it is created, and thus any changes to the pass by value within the function will not affect the value outside of the function.
- The exception to this is pointers, since those are essentially just addresses in memory—and so changing the value stored at that address, even within a separate function, will alter the value globally.
- Since arrays are also pointers, this same logic applies.
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;
}