C Functions
A function is a block of code that performs a specific task and can be called multiple times. Functions make your C programs modular, reusable, and easier to debug. Every C program has at least one function — main(). Learning to write your own functions is a major step in becoming a real C programmer.
Why Use Functions?
- Reusability — write once, call many times.
- Modularity — break complex programs into small, manageable chunks.
- Readability — code becomes self-documenting with meaningful function names.
- Debugging — bugs are easier to find in small, isolated functions.
- Teamwork — different developers can work on different functions.
Function Syntax
return_type function_name(parameters) {
// function body
return value; // if return_type != void
}
Example
int add(int a, int b) {
return a + b;
}
int— return type (returns an integer)add— function nameint a, int b— parametersreturn a + b;— returns the result
Your First Function
#include <stdio.h>
void greet() {
printf("Hello from Varanasi!\n");
}
int main() {
greet(); // Call the function
greet(); // Call again
return 0;
}
// Output:
// Hello from Varanasi!
// Hello from Varanasi!
void means the function doesn't return a value.
Functions with Parameters
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
int main() {
greet("Ankit"); // Hello, Ankit!
greet("Priya"); // Hello, Priya!
return 0;
}
Functions with Return Values
int square(int n) {
return n * n;
}
double average(int a, int b) {
return (a + b) / 2.0;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
printf("%d\n", square(5)); // 25
printf("%.2f\n", average(10, 20)); // 15.00
printf("%d\n", max(10, 20)); // 20
return 0;
}
Function Prototypes (Declaration)
In C, functions must be declared before they're used. You can declare a function first (prototype) and define it later.
#include <stdio.h>
// Function prototypes
int add(int a, int b);
void greet(char name[]);
int main() {
printf("%d\n", add(10, 20)); // 30
greet("Ankit");
return 0;
}
// Definitions come later
int add(int a, int b) {
return a + b;
}
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
Prototypes are optional if the function is defined before main(). But in real projects, always use prototypes — they let you organize code logically and catch type errors early.
Parameter Passing in C
C always passes arguments by value. The function gets a copy — modifications don't affect the original.
Call by Value
void change(int x) {
x = 100; // modifies local copy only
}
int main() {
int a = 5;
change(a);
printf("%d\n", a); // 5 — NOT changed
return 0;
}
Call by Reference (using pointers)
void change(int *x) {
*x = 100; // modifies original
}
int main() {
int a = 5;
change(&a);
printf("%d\n", a); // 100 — changed!
return 0;
}
Return Values
Single Value
int square(int n) {
return n * n;
}
void (no return)
void printLine() {
printf("----------\n");
// no return needed
}
Multiple Values — via Pointers
void minMax(int arr[], int size, int *min, int *max) {
*min = *max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < *min) *min = arr[i];
if (arr[i] > *max) *max = arr[i];
}
}
int main() {
int numbers[] = {5, 2, 8, 1, 9};
int min, max;
minMax(numbers, 5, &min, &max);
printf("Min: %d\n", min); // 1
printf("Max: %d\n", max); // 9
return 0;
}
Types of Functions
- Library functions — provided by C (printf, scanf, strlen, malloc).
- User-defined functions — you write them.
- Recursive functions — call themselves.
Recursion — Function Calling Itself
A recursive function calls itself with a smaller input. Every recursion needs a base case to stop.
Factorial
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // base case
}
return n * factorial(n - 1); // recursive case
}
printf("%d\n", factorial(5)); // 120
Fibonacci Series
int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
for (int i = 0; i < 8; i++) {
printf("%d ", fib(i));
}
// Output: 0 1 1 2 3 5 8 13
Sum of Digits
int sumDigits(int n) {
if (n == 0) return 0;
return (n % 10) + sumDigits(n / 10);
}
printf("%d\n", sumDigits(1234)); // 10
Every recursive function must have a base case. Without it, the function calls itself infinitely, causing a stack overflow and program crash. Recursion uses more memory than iteration.
Real Example — Calculator with Functions
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
double divide(int a, int b) {
if (b == 0) {
printf("Cannot divide by zero\n");
return 0;
}
return (double) a / b;
}
int main() {
int x = 20, y = 6;
printf("Sum: %d\n", add(x, y));
printf("Difference: %d\n", subtract(x, y));
printf("Product: %d\n", multiply(x, y));
printf("Quotient: %.2f\n", divide(x, y));
return 0;
}
Output
Sum: 26
Difference: 14
Product: 120
Quotient: 3.33
Real Example — Prime Check Function
#include <stdio.h>
#include <math.h>
int isPrime(int n) {
if (n <= 1) return 0;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main() {
for (int i = 1; i <= 20; i++) {
if (isPrime(i)) {
printf("%d ", i);
}
}
return 0;
}
// Output: 2 3 5 7 11 13 17 19
Scope Rules
- Local variables — declared inside a function, only accessible there.
- Global variables — declared outside all functions, accessible everywhere.
- Static local variables — retain value between function calls.
Static Variable Example
void counter() {
static int count = 0; // initialized once, persists
count++;
printf("Called %d times\n", count);
}
int main() {
counter(); // Called 1 times
counter(); // Called 2 times
counter(); // Called 3 times
return 0;
}
Storage Classes in C
auto - default for local variables
static - persists between calls; file-scoped if global
extern - declares a variable defined in another file
register - suggests storing in CPU register (rarely used)
Function Naming Conventions
- Use snake_case —
calculate_total,get_user_name - Start with a verb —
get,set,is,has,calculate - Boolean functions —
is_prime,is_even - Keep function names descriptive but short
Header Files — Organizing Functions
In real projects, functions are declared in .h (header) files and defined in .c files.
// math_utils.h
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int add(int a, int b);
int subtract(int a, int b);
#endif
// math_utils.c
#include "math_utils.h"
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
// main.c
#include "math_utils.h"
int main() {
printf("%d\n", add(10, 20));
return 0;
}
Rule of thumb: A function should do ONE thing and do it well. If a function is longer than 50 lines, split it into smaller functions. This is the single most important skill in writing maintainable code.
1. Write a function isEven(int n) that returns 1 if even, 0 if odd.
2. Write a function max(int a, int b, int c) that returns the largest of three.
3. Write a function reverse(int n) that returns the reversed number (123 → 321).
4. Write a recursive function power(int base, int exp).
5. Write a function swap(int *a, int *b) that swaps two numbers.
6. Write a function gcd(int a, int b) using Euclidean algorithm.
Quick Revision
- Functions = reusable blocks of code.
- Syntax:
return_type name(params) { ... }. void= no return value.- Prototypes declare functions before use.
- C passes arguments by value only.
- Use pointers to modify original variables.
- Return multiple values via pointers.
- Recursion needs a base case.
staticlocal variables persist between calls.- Functions make code modular, testable, and maintainable.
Interview Questions
Q: What is the difference between call by value and call by reference?
A: In call by value, a copy of the argument is passed — the original is not affected. In call by reference, the address is passed (via pointers) — the original can be modified.
Q: What is a function prototype?
A: A declaration of a function's signature (return type, name, parameters) before its actual definition. It tells the compiler what the function looks like so it can be called before being defined.
Q: What is the difference between void and int return type?
A: void means the function returns nothing. int means the function returns an integer. Use void for actions (print, modify) and int for computations.
Q: What is recursion? What are its disadvantages?
A: A function calling itself. It's elegant for problems like factorial, Fibonacci, and tree traversal. Disadvantages: uses more memory (stack), can cause stack overflow if too deep, and is often slower than iteration.
Q: Can a C function return multiple values?
A: No, it can return only one value. To return multiple values, use pointers (pass addresses of output variables) or return a struct.
Q: What is the difference between local and global variables?
A: Local — declared inside a function, accessible only there, destroyed when function returns. Global — declared outside all functions, accessible everywhere, lives for the entire program.
Q: What does the static keyword do in a function?
A: A static local variable is initialized only once and retains its value between function calls. It doesn't get destroyed when the function returns.
Q: How many return statements can a function have?
A: Any number of return statements, but only one executes per call. The function exits as soon as it hits a return. Non-void functions must return on every code path.
Q: What is the purpose of main() in C?
A: main() is the entry point of a C program. Execution starts from main(). It returns an int to the operating system (0 for success, non-zero for error).
Want to Master C Programming?
Join our C Programming course in Varanasi — practical classes and career support at our Sarnath centre.