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:
- You put something in → inputs (called parameters)
- The machine does its work → the function body
- You get something out → output (called the return value)
Defining and Calling a Function
c
1#include <stdio.h>23// 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 calculation8 return result; // send the answer back9}1011// 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 714 printf("3 + 4 = %d\n", sum); // prints: 3 + 4 = 71516 // You can call it multiple times with different inputs17 int another = add(10, 20);18 printf("10 + 20 = %d\n", another); // prints: 10 + 20 = 301920 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 return3}45// 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) files2int add(int a, int b);34// 2. void return — function does something but returns nothing5void 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}1011// 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}1617// 4. const parameters — promises not to modify the input18void print_label(const char *label) {19 printf("%s\n", label);20 // label[0] = 'X'; // compiler error — can't modify const21}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 22gpio_set_level(2, 0); // Turn off LED on GPIO 23vTaskDelay(pdMS_TO_TICKS(500)); // Wait 500msYou 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.

