Functions
Defining functions in C
Introduction
In this lesson, you'll learn about functions in C. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with defining functions in c.
C has its own approach to defining functions in c, which we'll explore step by step.
The C Way
Let's see how C handles this concept. Here's a typical example:
#include <stdio.h>
/* Declare before use (prototype) */
int add(int a, int b);
int add(int a, int b) {
return a + b;
}
/* No default params — use separate functions */
void greet(const char *name) {
printf("Hello, %s!\n", name);
}
void greetDefault() { greet("World"); }
/* Function pointer (callback) */
typedef int (*UnaryOp)(int);
int applyTwice(UnaryOp fn, int x) {
return fn(fn(x));
}
int doub(int x) { return x * 2; }
int main() {
printf("%d\n", applyTwice(doub, 3)); /* 12 */
return 0;
}Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
function add(a, b) { return a + b; }
function greet(name = "World") {
return "Hello, " + name + "!";
}
// Callback
function applyTwice(fn, x) { return fn(fn(x)); }
const double = x => x * 2;
console.log(applyTwice(double, 3)); // 12You may be used to different syntax or behavior.
C requires function prototypes (forward declarations) if definition comes later
You may be used to different syntax or behavior.
C has no default parameters — use separate functions
You may be used to different syntax or behavior.
C function pointers replace JS first-class functions/closures
You may be used to different syntax or behavior.
C functions cannot be nested inside other functions
Step-by-Step Breakdown
1. Function Prototypes
In C, if a function is called before its definition, you must declare a prototype first. JS hoists function declarations automatically.
// JS hoists: add(1,2) works even if defined laterint add(int a, int b); // prototype at top
// ... later ...
int add(int a, int b) { return a + b; }2. Function Pointers
C function pointers hold addresses of functions, enabling callbacks. They're verbose but powerful — the C equivalent of first-class functions.
function applyTwice(fn, x) { return fn(fn(x)); }typedef int (*UnaryOp)(int);
int applyTwice(UnaryOp fn, int x) { return fn(fn(x)); }3. Return Types
Every C function must declare its return type. void means no return value. The main function must return int.
Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- C requires function prototypes (forward declarations) if definition comes later
- C has no default parameters — use separate functions
- C function pointers replace JS first-class functions/closures
Key Takeaways
- Prototypes required if definition comes after first use
- No default params, no closures, no nested functions
- Function pointers enable callbacks
- Every function declares a return type