Function Declaration

Introduction

Function declaration in C tells the compiler about a function’s name, return type, and parameters before the function is actually defined or used. Also known as function prototype, it enables the compiler to perform type checking and allows functions to be called before their definition appears in the code.

Key Concepts

Function Prototype: Declaration without implementation Forward Declaration: Declaring function before definition Type Checking: Compiler validates parameter types Header Files: Common place for function declarations

Basic Syntax

// General syntax
return_type function_name(parameter_list);

// Examples
int add(int a, int b);
void printMessage(void);
float calculateArea(float radius);

Simple Examples

Basic Function Declarations

#include <stdio.h>

// Function declarations (prototypes)
int multiply(int x, int y);
void greet(char name[]);
float divide(float a, float b);

int main() {
    int result = multiply(5, 3);
    printf("Result: %d\n", result);
    
    greet("Alice");
    
    float quotient = divide(10.0, 3.0);
    printf("Quotient: %.2f\n", quotient);
    
    return 0;
}

// Function definitions
int multiply(int x, int y) {
    return x * y;
}

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

float divide(float a, float b) {
    if (b != 0) {
        return a / b;
    }
    return 0.0;
}

Parameter Declaration Styles

With Parameter Names

#include <stdio.h>

// Declarations with parameter names (preferred)
int power(int base, int exponent);
void swap(int *a, int *b);
double average(double arr[], int size);

int main() {
    printf("2^3 = %d\n", power(2, 3));
    
    int x = 10, y = 20;
    printf("Before swap: x=%d, y=%d\n", x, y);
    swap(&x, &y);
    printf("After swap: x=%d, y=%d\n", x, y);
    
    return 0;
}

int power(int base, int exponent) {
    int result = 1;
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }
    return result;
}

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

Without Parameter Names

#include <stdio.h>

// Declarations without parameter names (valid but less clear)
int subtract(int, int);
void printArray(int[], int);
char* findChar(char*, char);

int main() {
    printf("10 - 3 = %d\n", subtract(10, 3));
    return 0;
}

int subtract(int a, int b) {
    return a - b;
}

Function Declarations in Header Files

math_utils.h

#ifndef MATH_UTILS_H
#define MATH_UTILS_H

// Mathematical utility function declarations
int factorial(int n);
double squareRoot(double x);
int gcd(int a, int b);
int isPrime(int num);
double circleArea(double radius);

#endif

math_utils.c

#include "math_utils.h"
#include <math.h>

int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}

double squareRoot(double x) {
    return sqrt(x);
}

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int isPrime(int num) {
    if (num < 2) return 0;
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) return 0;
    }
    return 1;
}

double circleArea(double radius) {
    return 3.14159 * radius * radius;
}

Using the Header File

#include <stdio.h>
#include "math_utils.h"

int main() {
    printf("Factorial of 5: %d\n", factorial(5));
    printf("GCD of 12 and 8: %d\n", gcd(12, 8));
    printf("Is 17 prime? %s\n", isPrime(17) ? "Yes" : "No");
    printf("Area of circle (radius 3): %.2f\n", circleArea(3.0));
    
    return 0;
}

Advanced Declaration Examples

Function Pointers

#include <stdio.h>

// Function declarations
int add(int a, int b);
int multiply(int a, int b);

// Function pointer declaration
int (*operation)(int, int);

int main() {
    operation = add;
    printf("Addition: %d\n", operation(5, 3));
    
    operation = multiply;
    printf("Multiplication: %d\n", operation(5, 3));
    
    return 0;
}

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

int multiply(int a, int b) {
    return a * b;
}

Array Parameters

#include <stdio.h>

// Different ways to declare array parameters
void processArray1(int arr[], int size);
void processArray2(int *arr, int size);
void processArray3(int arr[10]);  // Size ignored
void processMatrix(int matrix[][3], int rows);

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    
    processArray1(numbers, 5);
    processMatrix(matrix, 2);
    
    return 0;
}

void processArray1(int arr[], int size) {
    printf("Array elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

void processMatrix(int matrix[][3], int rows) {
    printf("Matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

Variadic Functions

#include <stdio.h>
#include <stdarg.h>

// Declaration for variadic function
int sum(int count, ...);
void printInts(int count, ...);

int main() {
    printf("Sum of 3 numbers: %d\n", sum(3, 10, 20, 30));
    printf("Sum of 5 numbers: %d\n", sum(5, 1, 2, 3, 4, 5));
    
    printInts(4, 100, 200, 300, 400);
    
    return 0;
}

int sum(int count, ...) {
    va_list args;
    va_start(args, count);
    
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += va_arg(args, int);
    }
    
    va_end(args);
    return total;
}

void printInts(int count, ...) {
    va_list args;
    va_start(args, count);
    
    printf("Numbers: ");
    for (int i = 0; i < count; i++) {
        printf("%d ", va_arg(args, int));
    }
    printf("\n");
    
    va_end(args);
}

Real-World Example: Calculator Module

calculator.h

#ifndef CALCULATOR_H
#define CALCULATOR_H

// Basic arithmetic operations
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);

// Advanced operations
double power(double base, double exponent);
double percentage(double value, double percent);
double compound_interest(double principal, double rate, int time);

// Utility functions
int isValidNumber(double num);
void printResult(const char* operation, double result);

#endif

calculator.c

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

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

double subtract(double a, double b) {
    return a - b;
}

double multiply(double a, double b) {
    return a * b;
}

double divide(double a, double b) {
    if (b == 0) {
        printf("Error: Division by zero!\n");
        return 0;
    }
    return a / b;
}

double power(double base, double exponent) {
    return pow(base, exponent);
}

double percentage(double value, double percent) {
    return (value * percent) / 100.0;
}

double compound_interest(double principal, double rate, int time) {
    return principal * pow(1 + rate/100, time);
}

int isValidNumber(double num) {
    return !isnan(num) && !isinf(num);
}

void printResult(const char* operation, double result) {
    if (isValidNumber(result)) {
        printf("%s result: %.2f\n", operation, result);
    } else {
        printf("Invalid result for %s\n", operation);
    }
}

Best Practices

Clear Parameter Names

// Good - descriptive parameter names
int calculateDistance(int x1, int y1, int x2, int y2);
void saveToFile(const char* filename, const char* data);

// Poor - unclear parameter names
int calc(int a, int b, int c, int d);
void save(char* f, char* d);

Const Correctness

// Use const for parameters that shouldn't be modified
int stringLength(const char* str);
void printArray(const int arr[], int size);
double calculateArea(const double radius);

Consistent Style

// Consistent declaration style
int processData(const char* input, char* output, int maxLength);
int validateInput(const char* data, int minLength, int maxLength);
int convertFormat(const char* source, char* dest, int format);

Common Mistakes

  1. Missing Semicolon: Function declarations must end with semicolon
  2. Parameter Mismatch: Declaration and definition parameters must match
  3. Missing Prototypes: Can lead to implicit function declarations
  4. Header Guards: Always use header guards in header files

Summary

Function declarations are essential for proper C programming, enabling type checking and code organization. They should include clear parameter names, appropriate const qualifiers, and be placed in header files for modularity. Proper function declarations improve code maintainability, enable separate compilation, and help catch errors at compile time rather than runtime.


Part of BCA Programming with C Course (UGCOA22J201)