SyntaxStudy
Sign Up
C Declaring and Defining Functions
C Beginner 1 min read

Declaring and Defining Functions

In C, a function must be declared before it is called. A declaration (also called a prototype) tells the compiler the function's name, return type, and parameter types without providing the body. The definition provides the actual body. Placing prototypes in header files and definitions in `.c` source files is the standard way to split a program across multiple compilation units. A function's return type can be any C type, including pointers and structs. The `void` return type means the function produces no value. Parameters are listed in the parentheses; an empty parameter list declared as `(void)` explicitly states the function takes no arguments. In C89, an empty `()` means the parameter list is unspecified, which is different and less safe. Functions can be called recursively — a function that calls itself. Every recursive call creates a new stack frame with its own local variables. Recursion is natural for algorithms like factorial, Fibonacci, and tree traversal, but deep recursion can overflow the call stack. Iterative solutions are often preferred for performance-sensitive code, and tail-call optimisation (which GCC can perform with `-O2`) can sometimes eliminate the overhead.
Example
#include <stdio.h>

/* Prototypes — declared before main so main can call them */
int    add(int a, int b);
double power(double base, int exp);
unsigned long factorial(unsigned int n);

int main(void)
{
    printf("add(3, 4)        = %d\n",     add(3, 4));
    printf("power(2.0, 10)   = %.0f\n",   power(2.0, 10));
    printf("factorial(10)    = %lu\n",    factorial(10));
    return 0;
}

/* Definitions */
int add(int a, int b)
{
    return a + b;
}

double power(double base, int exp)
{
    double result = 1.0;
    for (int i = 0; i < exp; i++)
        result *= base;
    return result;
}

/* Recursive factorial */
unsigned long factorial(unsigned int n)
{
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}