Functions help us organize code into small, reusable pieces. Declaration tells the program about a function's name and inputs, while definition gives the actual instructions.
Function declaration and definition in C++
return_type function_name(parameter_list); // Function declaration return_type function_name(parameter_list) { // function body (code) }
The return_type tells what kind of value the function gives back.
The parameter_list is the list of inputs the function needs, inside parentheses.
add that takes two integers and returns their sum.int add(int a, int b); // Declaration int add(int a, int b) { return a + b; }
greet that prints a message and returns nothing (void).void greet(); // Declaration void greet() { std::cout << "Hello!" << std::endl; }
multiply that multiplies two decimal numbers.double multiply(double x, double y); // Declaration double multiply(double x, double y) { return x * y; }
This program declares a function square before main. Then it defines it after main. The function calculates the square of a number.
#include <iostream> // Function declaration int square(int number); int main() { int num = 5; std::cout << "Square of " << num << " is " << square(num) << std::endl; return 0; } // Function definition int square(int number) { return number * number; }
You can declare a function before main and define it later in the code.
If you define a function before main, you don't need a separate declaration.
Function declarations help the compiler know about functions used before their definitions.
Function declaration tells the program about a function's name, return type, and parameters.
Function definition provides the actual code that runs when the function is called.
Separating declaration and definition helps organize code and allows reuse.