C Programming: Functions Tutorial

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

Function

1. Function Declaration

Function Declaration (or prototype) tells the compiler about a function's name, return type, and parameters before its actual definition. It allows you to call the function before its actual definition in the code.

Example:


#include <stdio.h>

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

int main() {
    int result = add(5, 3); // Function call
    printf("The sum is %d\\n", result);
    return 0;
}

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

Function Declaration: int add(int a, int b); tells the compiler that there is a function named add that takes two integers and returns an integer.

Function Definition: int add(int a, int b) { return a + b; } provides the actual code for the function.

2. Function Calls

Function Calls are where you invoke or use a function in your code. The function must be declared before it is used.

Example:


#include <stdio.h>

int multiply(int x, int y);

int main() {
    int product = multiply(4, 5); // Function call
    printf("The product is %d\\n", product);
    return 0;
}

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

Function Call: multiply(4, 5) calls the multiply function, passing 4 and 5 as arguments.

Return Value: The function returns the result of x * y, which is stored in the product variable.

3. Function Overloading

Function Overloading allows you to define multiple functions with the same name but different parameters. However, note that C does not support function overloading directly. Instead, you might use different function names or write a function that can handle varying arguments using techniques such as varargs. Function overloading is commonly used in C++.

Example in C++:


#include <iostream>
using namespace std;

// Function Overloading in C++
int add(int a, int b) {
    return a + b;
}

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

int main() {
    cout << "Sum of integers: " << add(5, 3) << endl;
    cout << "Sum of doubles: " << add(5.5, 3.2) << endl;
    return 0;
}

Function Overloading: Here, add is overloaded to handle both int and double types.

Function Call: The appropriate add function is called based on the argument types.

Previous Next
Modern Footer