HOME HTML EDITOR C JAVA PHP

C Functions:

A **Function** is a self-contained block of statements that carries out a specific task. Every C program has at least one function, which is main(). Functions help in achieving **code reusability** and **modularity**, making the program easier to read, test, and maintain.

1. The Structure of a Function

A function consists of two main parts: the **Declaration** (or Prototype) and the **Definition**. To use a function, you must also **Call** it.

2. Creating and Calling a Function

In C, you usually declare a function above main() and define it later, or define it entirely above main() so the compiler knows it exists.

#include <stdio.h>

// Function definition
void greetUser() {
    printf("Hello, welcome to C programming!\n");
}

int main() {
    greetUser(); // Function Call
    greetUser(); // Calling it again (Reusability!)
    return 0;
}

3. Function Parameters and Arguments

Parameters act as placeholders for data you send into the function. When you call the function and pass real values, those values are called **Arguments**.

void printSum(int a, int b) {
    printf("Sum is: %d\n", a + b);
}

int main() {
    printSum(5, 10); // 5 and 10 are arguments
    return 0;
}

4. The Return Keyword

Most functions perform a calculation and need to send the result back to the caller. We use the return keyword for this. The return value must match the **Return Type** declared at the start of the function.

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

int main() {
    int result = multiply(4, 3);
    printf("Result: %d", result); // Output: 12
    return 0;
}

5. Scope of Variables in Functions

Variables declared inside a function are called **Local Variables**. They only exist within that function and cannot be accessed from main() or other functions. Conversely, **Global Variables** are declared outside all functions and are accessible everywhere.

6. Pass by Value vs. Pass by Reference

Method Description
Pass by Value A copy of the data is sent. Changing it inside the function does NOT change the original variable.
Pass by Reference The memory address (pointer) is sent. Changing it inside the function DOES change the original variable.

7. Recursion

C allows a function to call itself. This is known as **Recursion**. It is a powerful tool for solving problems that can be broken down into smaller, similar sub-problems (like calculating factorials or Fibonacci numbers).

int factorial(int n) {
    if (n == 0) return 1; // Base case
    return n * factorial(n - 1); // Recursive call
}
Pro Tip: In professional development, keep your functions "Single Responsibility." A function should do exactly one thing well. If your function is getting too long (more than 20-30 lines), it’s usually a sign you should break it into two smaller functions.