Function Definition vs Declaration
What you'll learn: You'll learn the key difference between telling the compiler a function exists (declaration) versus telling it what the function does (definition).
The Core Idea
In many programming languages (like C, C++), you need to introduce a function to the compiler before you can use it. There are two ways to do this:
-
Function Declaration (also called a prototype): This announces that a function exists, specifying its name, return type, and parameters—but not the actual code inside. Think of it like a preview or promise: "A function named
calculateSumexists and takes two integers." -
Function Definition (also called an implementation): This provides the complete function, including the declaration information plus the actual body of code that executes when the function is called.
A Simple Analogy
Imagine a restaurant menu versus the kitchen recipe:
- The menu (declaration) tells you "Spaghetti Carbonara exists, costs $12, serves 1" — you know it's available, but not how it's made.
- The recipe (definition) gives you the full instructions: ingredients, steps, everything needed to actually make the dish.
Why the Distinction Matters
Sometimes you want to declare a function early in your code so other parts can reference it, but define it later (or in another file). The declaration lets the compiler verify you're using the function correctly, even before seeing the full implementation.
Key Takeaway: A function declaration is a forward announcement (prototype) that tells the compiler about a function's signature, while a function definition provides the complete implementation with the actual code body.