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

price
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;
}
  1. price ← 50

    7int main(void) {8    int price→ 50 = 50; //@price=30, 809    int total = addTax(price50);10    printf("total=%d\n", total);
  2. int addTax(int price)

    3int addTax(int price50) {4    return price50 + price / 10;5}
  3. 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
  1. price ← 30

    7int main(void) {8    int price→ 30 = 30;9    int total = addTax(price30);10    printf("total=%d\n", total);
  2. int addTax(int price)

    3int addTax(int price30) {4    return price30 + price / 10;5}
  3. total ← 33

    8    int price = 30;9    int total→ 33 = addTax(price30);10    printf("total=%d\n", total33);11    return 0;12}
    outputtotal=33
  1. price ← 80

    7int main(void) {8    int price→ 80 = 80;9    int total = addTax(price80);10    printf("total=%d\n", total);
  2. int addTax(int price)

    3int addTax(int price80) {4    return price80 + price / 10;5}
  3. 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

  1. price starts at 50.
  2. addTax(price) receives 50.
  3. price / 10 uses integer division, so 50 / 10 is 5.
  4. The function returns 50 + 5, which is 55.
  5. 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.