Ch6.2: Declarations and Definitions
Overview
In C++, every function must be declared before it is used. A function may also be defined separately. Understanding the difference between declarations and definitions is essential for organizing code across multiple files, and even in small programs it helps clarify how the compiler reads your code.
In this chapter, you will learn:
- what a function declaration is
- what a function definition is
- why declarations are needed
- how declarations enable calling functions before their definitions
- why declarations usually go in headers
- why
int x();is a function declaration, not a variable
1. Function definition
A definition provides the full body of the function.
int add(int a, int b)
{
return a + b;
}
This both declares and defines the function.
2. Function declaration
A declaration tells the compiler that a function exists, but does not provide the body.
int add(int a, int b); // declaration
A declaration ends with a semicolon and has no body.
Later, the function is defined:
int add(int a, int b) // definition
{
return a + b;
}
3. Why declarations are needed
The compiler reads your program from top to bottom. If you call a function before the compiler has seen it, you must provide a declaration first.
#include <fast_io.h>
int add(int a, int b); // declaration
int main()
{
using namespace ::fast_io::iomnp;
println(add(3, 4)); // OK
}
int add(int a, int b) // definition
{
return a + b;
}
Without the declaration, the call inside main would be an error.
4. Declarations usually go in headers
In real projects, declarations are placed in header files
(.h or .hpp), and definitions go in
source files (.cpp).
math.hpp:
-----------
int add(int a, int b);
math.cpp:
-----------
int add(int a, int b)
{
return a + b;
}
This allows multiple source files to use the same function by including the header.
4.1 A common mistake: int x(); is a function declaration
In C++, the syntax int x(); does not create a
variable. It declares a function named x that
takes no arguments and returns an int.
int main()
{
int x(); // ❌ NOT a variable — this declares a function
::fast_io::string str(); // ❌ also a function declaration
}
This rule applies to any type, including user‑defined types and
::fast_io::string.
Correct ways to define variables
For built‑in types:
int x{}; // ✔ value-initialized variable
For ::fast_io::string:
::fast_io::string str; // ✔ default-constructed string
In modern C++, prefer {} initialization for built‑in types to avoid
confusion with function declarations.
5. Summary
- A declaration introduces a function’s name, parameters, and return type.
- A definition provides the function body.
- A definition also counts as a declaration.
- You need a declaration before calling a function.
- Declarations usually go in headers; definitions go in source files.
int x();declares a function, not a variable.- Use
{}for built‑in variable initialization. - Use
::fast_io::string str;to create a string variable.