Functions

Types of Function Outputs

  1. Side-effect
  2. Return values, variables

Args

You must define args and return type. For example, the meow function, which takes void and returns void:

void meow(void) {
    printf("meow");
}

Example: Function Args

void meow(int n) {
    for (int i = 0; i < n; i++)
    {
        printf("meow");
    }
}

Style: Keeping main() at the top

Suppose we want to keep main() at the top of a file and some functions at the bottom.

We can tell the compiler to define the functions necessary by putting the void meow(void); pattern above main like this:

#include <stdio.h>

void meow(int n);

int main(void)
{
    meow(3);
}

void meow(int n) {
    for (int i = 0; i < n; i++)
    {
        printf("meow");
    }
}

This (void meow(void);) creates a prototype that says what the function returns and takes without defining it yet.

We could also create a header file

Returning a Value

Example:

float discount(float price, float percentOff)
{
    return price * (100 - percentOff) / 100;
}