Functions (Lesson)

Functions in C

A function is a group of statements that together perform a task. Functions allow for Modularity, Reusability, and Readability.

9.1 Anatomy of a Function

To use a function, you need:

  1. Declaration (Prototype): Tells the compiler the name, return type, and parameters.
  2. Definition: The actual body containing the logic.
  3. Call: Invoking the function to perform its task.
#include <stdio.h>

// 1. Declaration
int addNumbers(int a, int b);

int main() {
    int n1 = 5, n2 = 10, result;
    // 3. Call
    result = addNumbers(n1, n2);
    printf("Sum = %d", result);
    return 0;
}

// 2. Definition
int addNumbers(int a, int b) {
    return a + b;
}

9.2 Parameter Passing Techniques

Call by Value

A copy of the actual variable is passed. Changes made inside the function do not affect the original variable.

void update(int x) { x = 10; }
// Calling update(a) will not change 'a' in main.

Call by Reference

The address of the variable is passed using pointers. Changes made inside the function affect the original variable.

void update(int *x) { *x = 10; }
// Calling update(&a) WILL change 'a' in main.

9.3 Standard Library Functions

C provides hundreds of built-in functions.

  • math.h: sqrt(), pow(), ceil(), floor()
  • string.h: strlen(), strcpy(), strcmp()
  • time.h: time(), ctime()

9.4 Benefits of Using Functions

  • No Redundancy: Write once, use many times.
  • Easier Maintenance: Fix a bug in a function, and it's fixed everywhere.
  • Abstraction: Use functions like printf() without knowing their internal logic.

Example: Power Function

#include <stdio.h>
#include <math.h>

int main() {
    double base, exp, res;
    printf("Enter base: ");
    scanf("%lf", &base);
    printf("Enter exponent: ");
    scanf("%lf", &exp);

    // Using library function from math.h
    res = pow(base, exp);

    printf("%.2lf ^ %.2lf = %.2lf", base, exp, res);

    return 0;
}

Refer to the Lecture Slides for a diagram of the Function Call Stack Mechanism.

PREVIOUS
Scope of Variables
NEXT
Functions Continued