C Refresher

Functions & Scope

A function is a reusable block of code that does one specific job. Instead of writing the same code over and over, you write it once, give it a name, and call it whenever you need it.


The Vending Machine Analogy

Think of a function like a vending machine:

  1. You put something in → inputs (called parameters)
  2. The machine does its work → the function body
  3. You get something out → output (called the return value)

Defining and Calling a Function

c
1#include <stdio.h>
2
3// Step 1: DEFINE the function (write the recipe)
4// "int" = return type (what comes out)
5// "a" and "b" = parameters (what goes in)
6int add(int a, int b) {
7 int result = a + b; // do the calculation
8 return result; // send the answer back
9}
10
11// Step 2: CALL the function (use the recipe)
12int main(void) {
13 int sum = add(3, 4); // call add with 3 and 4 → sum becomes 7
14 printf("3 + 4 = %d\n", sum); // prints: 3 + 4 = 7
15
16 // You can call it multiple times with different inputs
17 int another = add(10, 20);
18 printf("10 + 20 = %d\n", another); // prints: 10 + 20 = 30
19
20 return 0;
21}

Functions That Don't Return a Value (void)

Sometimes a function just does something without giving back a result. Use void as the return type:

c
1void greet(const char *name) { // void = "nothing comes out"
2 printf("Hello, %s!\n", name); // just print, no return
3}
4
5// Call it:
6greet("Rajath"); // prints: Hello, Rajath!
7greet("ESP32"); // prints: Hello, ESP32!

Advanced Function Features

As you read ESP-IDF source code, you will see functions declared with specific keywords that change how they behave.

c
1// 1. Function declaration (prototype) — common in header (.h) files
2int add(int a, int b);
3
4// 2. void return — function does something but returns nothing
5void blink_led(int gpio, int delay_ms) {
6 gpio_set_level(gpio, 1);
7 vTaskDelay(pdMS_TO_TICKS(delay_ms));
8 gpio_set_level(gpio, 0);
9}
10
11// 3. static — limits the function's scope to THIS file only (.c file)
12static void helper_function(void) {
13 // Only code inside the exact same file can call this.
14 // It hides the function from the rest of the project.
15}
16
17// 4. const parameters — promises not to modify the input
18void print_label(const char *label) {
19 printf("%s\n", label);
20 // label[0] = 'X'; // compiler error — can't modify const
21}

Why Functions Matter in ESP-IDF

Every peripheral in ESP-IDF is controlled through functions:

c
1gpio_set_level(2, 1); // Turn on LED on GPIO 2
2gpio_set_level(2, 0); // Turn off LED on GPIO 2
3vTaskDelay(pdMS_TO_TICKS(500)); // Wait 500ms

You don't need to know how these work internally — you just need to know what to put in and what comes out. That is the true power of functions and modular programming.

Previous
Bit Manipulation