Foundations
Functions
A function names reusable work and can return a computed value.
parameter
A parameter receives the value passed by the caller.
return
`return` sends a value back to the caller.
Functions
functions.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int addTax(int price) {
return price + price / 10;
}
int main(void) {
int price = 50;
int total = addTax(price);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int addTax(int price) {
return price + price / 10;
}
int main(void) {
int price = 30;
int total = addTax(price);
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int addTax(int price) {
return price + price / 10;
}
int main(void) {
int price = 80;
int total = addTax(price);
printf("total=%d\n", total);
return 0;
}
price ← 50
7int main(void) {8 int price→ 50 = 50; //@price=30, 809 int total = addTax(price50);10 printf("total=%d\n", total);int addTax(int price)
3int addTax(int price50) {4 return price50 + price / 10;5}total ← 55
8 int price = 50; //@price=30, 809 int total→ 55 = addTax(price50);10 printf("total=%d\n", total55);11 return 0;12}outputtotal=55
price ← 30
7int main(void) {8 int price→ 30 = 30;9 int total = addTax(price30);10 printf("total=%d\n", total);int addTax(int price)
3int addTax(int price30) {4 return price30 + price / 10;5}total ← 33
8 int price = 30;9 int total→ 33 = addTax(price30);10 printf("total=%d\n", total33);11 return 0;12}outputtotal=33
price ← 80
7int main(void) {8 int price→ 80 = 80;9 int total = addTax(price80);10 printf("total=%d\n", total);int addTax(int price)
3int addTax(int price80) {4 return price80 + price / 10;5}total ← 88
8 int price = 80;9 int total→ 88 = addTax(price80);10 printf("total=%d\n", total88);11 return 0;12}outputtotal=88
Follow the Function Call
pricestarts at50.addTax(price)receives50.price / 10uses integer division, so50 / 10is5.- The function returns
50 + 5, which is55. - The program prints
total=55. | price | tax part | returned total | | --- | --- | --- | | 30 | 3 | 33 | | 50 | 5 | 55 | | 80 | 8 | 88 |
Exercise: functions.c
Reproduce total=55, then use the pinned prices 30 and 80 to predict each returned total.