Functions in C

A function is a self-contained, reusable block of code that performs a specific task. Instead of writing the same code repeatedly, it is placed inside a function once and called wherever needed. Functions make programs organized, readable, and easy to maintain.

Every C program has at least one function — the main() function. Other functions can be created as needed.

Why Use Functions?

  • Reusability: Write once, use many times in the same or other programs.
  • Modularity: Break a large problem into smaller, manageable pieces.
  • Readability: Programs are easier to read and understand.
  • Easy Debugging: Isolate and fix errors in specific functions.
  • Teamwork: Multiple developers can work on different functions simultaneously.

Types of Functions in C

  1. Library Functions — built-in functions provided by C (e.g., printf(), scanf(), sqrt())
  2. User-Defined Functions — functions created by the programmer

Structure of a User-Defined Function

Every user-defined function has three parts:

1. Function Declaration (Prototype)

Tells the compiler that the function exists and what to expect from it — its name, return type, and parameter types. It is placed before main().


return_type function_name(parameter_type1, parameter_type2, ...);

2. Function Definition

The actual body of the function — what it does.


return_type function_name(parameter declarations)
{
    // function body
    // ...
    return value; // only needed if return_type is not void
}

3. Function Call

Invokes (runs) the function from within main() or another function.


function_name(argument1, argument2, ...);

Simple Function Example — No Parameters, No Return Value


#include <stdio.h>

// Function declaration (prototype)
void greet();

int main()
{
    greet();   // function call
    greet();   // can be called multiple times
    return 0;
}

// Function definition
void greet()
{
    printf("Hello! Welcome to C Programming.\n");
}

Output


Hello! Welcome to C Programming.
Hello! Welcome to C Programming.

Function with Parameters

Parameters allow passing data to a function. When the function is called, values (called arguments) are passed inside the parentheses.


#include <stdio.h>

void greetUser(char name[])
{
    printf("Hello, %s! Welcome.\n", name);
}

int main()
{
    greetUser("Alice");
    greetUser("Bob");
    return 0;
}

Output


Hello, Alice! Welcome.
Hello, Bob! Welcome.

Function with Return Value

A function can compute a result and return it using the return statement. The return type must match what is declared.


#include <stdio.h>

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

int main()
{
    int result = add(10, 5);
    printf("Sum = %d\n", result);  // Sum = 15

    printf("Sum = %d\n", add(20, 30));  // Sum = 50

    return 0;
}

Function with Parameters and Return Value


#include <stdio.h>

float calculateArea(float length, float width)
{
    return length * width;
}

int main()
{
    float area = calculateArea(8.5, 4.0);
    printf("Area = %.2f sq. units\n", area);
    return 0;
}

Output


Area = 34.00 sq. units

The Four Function Types in C

TypeParametersReturn ValueExample
Type 1NoNo (void)void greet()
Type 2NoYesint getNumber()
Type 3YesNo (void)void display(int n)
Type 4YesYesint add(int a, int b)

Call by Value

In C, function arguments are passed by value by default. This means a copy of the variable is passed to the function. Any changes made to the parameter inside the function do not affect the original variable.


#include <stdio.h>

void doubleIt(int num)
{
    num = num * 2;
    printf("Inside function: %d\n", num);
}

int main()
{
    int x = 5;
    doubleIt(x);
    printf("Outside function: %d\n", x);  // x is still 5!
    return 0;
}

Output


Inside function: 10
Outside function: 5

The original value of x remains unchanged because only a copy was passed.

Call by Reference (Using Pointers)

To change the original variable inside a function, pass its address using pointers.


#include <stdio.h>

void doubleIt(int *num)
{
    *num = *num * 2;  // modifying the actual value
}

int main()
{
    int x = 5;
    doubleIt(&x);  // passing address
    printf("After doubleIt: %d\n", x);  // x is now 10!
    return 0;
}

Output


After doubleIt: 10

Function Scope — Local vs Global

Variables declared inside a function are local — they only exist within that function. Variables declared outside all functions are global — accessible from anywhere in the program.


#include <stdio.h>

int globalScore = 100;  // global variable

void showScore()
{
    int bonus = 10;  // local variable
    printf("Score: %d, Bonus: %d\n", globalScore, bonus);
}

int main()
{
    showScore();
    // printf("%d", bonus);  // ERROR! bonus is local to showScore
    return 0;
}

Practical Example — Find Maximum of Two Numbers


#include <stdio.h>

int findMax(int a, int b)
{
    if (a > b)
        return a;
    else
        return b;
}

int main()
{
    int x = 45, y = 78;
    int maximum = findMax(x, y);
    printf("Maximum = %d\n", maximum);  // Maximum = 78
    return 0;
}

Practical Example — Check Prime Number


#include <stdio.h>

int isPrime(int n)
{
    if (n <= 1) return 0;  // not prime

    for (int i = 2; i * i <= n; i++)
    {
        if (n % i == 0)
            return 0;  // not prime
    }
    return 1;  // prime
}

int main()
{
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);

    if (isPrime(num))
        printf("%d is Prime.\n", num);
    else
        printf("%d is Not Prime.\n", num);

    return 0;
}

Summary

Functions are one of the most important concepts in C programming. They divide a large program into smaller, reusable pieces. A function has a declaration (prototype), a definition (body), and is invoked via a function call. Functions can accept parameters and return values. By default, C uses call by value — passing a copy. To modify original values, pass by reference using pointers. Writing well-designed functions leads to programs that are clean, easy to debug, and easy to extend.

Leave a Comment

Your email address will not be published. Required fields are marked *