Functions
Declaration vs Definition
// Declaration (prototype) - no body, ends with a semicolon
int add(int a, int b);
// Definition - includes the body
int add(int a, int b) {
return a + b;
}Anatomy of a Function
returnType functionName(parameterType parameterName, ...) {
// function body
return value; // only if returnType is not void
}The void Return Type
void as its return type. A void function can still use a bare return; to exit early, but it cannot return a value.#include <iostream>
using namespace std;
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
// no return statement needed
}
int main() {
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
return 0;
}Calling Functions
Calling a function means using its name followed by parentheses containing any required arguments. The function's return value (if any) can be stored, printed, or used directly in an expression.
#include <iostream>
using namespace std;
int square(int x) {
return x * x;
}
int main() {
int result = square(5); // store the return value
cout << result << endl; // Output: 25
cout << square(3) + 1 << endl; // Output: 10 - used directly in an expression
return 0;
}Where to Declare: Before Use, or Forward Declare
C++ compiles top to bottom and needs to know a function's signature before it's called. You can satisfy this in two ways: define the function above where it's first used, or write a forward declaration near the top of the file (or in a header) and define the function anywhere afterward.
#include <iostream>
using namespace std;
int add(int a, int b); // forward declaration
int main() {
cout << add(2, 3) << endl; // works - compiler already knows the signature
return 0;
}
// definition can come after main()
int add(int a, int b) {
return a + b;
}'add' was not declared in this scope. Forward declarations (and header files, which are essentially collections of them) are how larger C++ programs organize functions across files while still following this top-to-bottom rule.Key Points
A declaration gives the compiler a function's signature; a definition provides its body.
Header files hold declarations so other files can call a function without seeing its implementation.
void functions perform an action but return no value; return; can still exit early.
A function must be declared (or defined) before its first call in a file.
Every code path in a non-void function must return an appropriate value.