0
0
C++programming~5 mins

Function declaration and definition in C++

Choose your learning style9 modes available
Introduction

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.

When you want to reuse the same code multiple times without rewriting it.
When you want to split a big task into smaller, easier steps.
When you want to tell the program about a function before using it in the code.
When you want to keep your code clean and easy to read.
When you want to separate the function's interface from its details.
Syntax
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.

Examples
This declares and defines a function add that takes two integers and returns their sum.
C++
int add(int a, int b);  // Declaration

int add(int a, int b) {
    return a + b;
}
This declares and defines a function greet that prints a message and returns nothing (void).
C++
void greet();  // Declaration

void greet() {
    std::cout << "Hello!" << std::endl;
}
This declares and defines a function multiply that multiplies two decimal numbers.
C++
double multiply(double x, double y);  // Declaration

double multiply(double x, double y) {
    return x * y;
}
Sample Program

This program declares a function square before main. Then it defines it after main. The function calculates the square of a number.

C++
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.