0
0
Cprogramming~5 mins

Function declaration and definition

Choose your learning style9 modes available
Introduction

Functions help you organize your code into small, reusable blocks. You declare a function to tell the program it exists, and define it to explain what it does.

When you want to reuse a piece of code multiple times without rewriting it.
When you want to make your program easier to read by breaking it into smaller parts.
When you want to separate the description of a function from its actual code, for example in large projects.
When you want to share function declarations in header files and define them in source files.
When you want to test parts of your program independently.
Syntax
C
return_type function_name(parameter_list);  // Function declaration

return_type function_name(parameter_list) {
    // function body (definition)
}

The return_type tells what type of value the function will give back.

The parameter_list is a list of inputs the function needs, or empty if none.

Examples
This is a declaration of a function named add that takes two integers and returns an integer.
C
int add(int a, int b);
This is the definition of the add function. It adds two numbers and returns the result.
C
int add(int a, int b) {
    return a + b;
}
This shows a function greet that takes no inputs and returns nothing (void). It prints a greeting.
C
void greet(void);

void greet(void) {
    printf("Hello!\n");
}
Sample Program

This program declares a function multiply before main. Then it defines it after main. The program calls multiply to multiply 4 and 5 and prints the result.

C
#include <stdio.h>

// Function declaration
int multiply(int x, int y);

int main() {
    int result = multiply(4, 5);
    printf("4 times 5 is %d\n", result);
    return 0;
}

// Function definition
int multiply(int x, int y) {
    return x * y;
}
OutputSuccess
Important Notes

Function declaration is optional if the function is defined before it is used.

Always match the declaration and definition exactly (same return type, name, and parameters).

Use void in parameters if the function takes no arguments.

Summary

Declare functions to tell the program about them before use.

Define functions to explain what they do.

Functions help keep code organized and reusable.