C Functions

A function is a block of code with a name, which does one job. You write it once and call it whenever needed. Every C program has at least one function, main().

Why use functions?

  • The code is reused, so you do not repeat it.
  • A big program is divided into small parts, which are easy to read and test.
  • Errors are easier to find and fix.

Three parts of a function

PartMeaningExample
Declaration (prototype)Tells the compiler the name, return type and parametersint add(int a, int b);
DefinitionThe code of the functionint add(int a, int b) { ... }
CallRuns the functionadd(5, 3);

Example

#include <stdio.h>

int add(int a, int b);        // declaration

int main(void) {
    int result = add(5, 3);   // call
    printf("Sum = %d\n", result);
    return 0;
}

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

Output:

Output of the above program is

Sum = 8

Function with no return value

Use void when the function does not return anything.

#include <stdio.h>

void greet(void) {
    printf("Welcome to C functions\n");
}

int main(void) {
    greet();
    greet();
    return 0;
}

Output:

Output of the above program is

Welcome to C functions
Welcome to C functions

Return a value

#include <stdio.h>

int isEven(int n) {
    return n % 2 == 0;     // 1 for true, 0 for false
}

int main(void) {
    printf("%d\n", isEven(10));
    printf("%d\n", isEven(7));
    return 0;
}

Output:

Output of the above program is

1
0

Note: If you write the function after main(), you must declare it before main(). Or you can define the whole function above main() and skip the declaration.

Next: C Function Arguments and Return Value.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to find the factorial of a number using recursion
Write a C program to swap two numbers using a function and pointers
Interview Questions & Answers
What is the difference between call by value and call by reference in C?
What is recursion in C?
What is the difference between local and global variables in C?
What are storage classes in C?
What is the use of the static keyword in C?