C Language
5. Functions & RecursionIntermediate10 min read

Functions & Modular Programming in C

Write clean, modular code with function prototypes, parameter passing (Call by Value vs Call by Reference), and return types.

Key Takeaways & Core Concepts
  • A function prototype declares name, return type, and parameter types before main().
  • C strictly passes arguments by value: a copy of each argument is pushed onto the stack frame.
  • To modify caller variables (Call by Reference), you must pass memory addresses (pointers).
  • Functions prevent code duplication and enable modular, testable software.

Function Declaration, Definition & Invocation

A C function consists of:

  • Return Type: Type of value returned (int, void, double, etc.).
  • Function Name: Identifier used to call the function.
  • Parameters: Comma-separated variable declarations enclosed in parentheses.
  • Body: Code statements wrapped in curly braces.
C Code Example
1// Function Prototype (Declaration)
2int add(int a, int b);
3
4int main(void) {
5 int sum = add(5, 7); // Invocation
6 return 0;
7}
8
9// Function Definition
10int add(int a, int b) {
11 return a + b;
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines

Call by Value vs. Call by Reference

Understanding how parameters are passed to functions is vital:

  • Call by Value: The function receives a copy of the argument. Changes made to parameters inside the function do not affect caller variables.
  • Call by Reference (via Pointers): The function receives the memory address of the caller variable. Modifying the dereferenced pointer directly alters the original caller data.
Classic Swap: Value vs Pointer Reference
1#include <stdio.h>
2
3// Call by Value: Does NOT swap original values
4void swapByValue(int a, int b) {
5 int temp = a;
6 a = b;
7 b = temp;
8}
9
10// Call by Reference: Swaps caller's actual memory
11void swapByReference(int *a, int *b) {
12 int temp = *a;
13 *a = *b;
14 *b = temp;
15}
16
17int main(void) {
18 int x = 10, y = 20;
19
20 printf("Original: x = %d, y = %d\n", x, y);
21 swapByValue(x, y);
22 printf("After swapByValue: x = %d, y = %d (Unchanged!)\n", x, y);
23
24 swapByReference(&x, &y); // Passing memory addresses
25 printf("After swapByReference: x = %d, y = %d (Swapped!)\n", x, y);
26
27 return 0;
28}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
28 lines
Note: swapByReference takes pointer parameters (int *a) and receives the address of x and y (&x, &y), enabling in-place mutation.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

How does C natively pass arguments to functions by default?

Intermediate