C guide
  • Hello reader!
  • C programming
    • C
    • Roadmap
    • Basics
      • Variables in C
      • I/O in C
      • Data types
      • Operators
      • Control Flow
      • Arrays
        • Strings (char arrays)
        • Multidimensional Arrays
    • Functions!
      • Recursion
  • Pointers
    • Pointer-Array Relationship
  • Structures and Unions
  • Dynamic memory allocation
  • File I/O (Input/Output)
  • Advanced topics
  • Debugging & Optimization
  • Practices
  • Cheatsheet
Powered by GitBook
On this page

Was this helpful?

  1. C programming

Functions!

What is a Function?

A function is a block of code that performs a specific task. Instead of repeating code, you can call a function whenever you need it. Functions can take inputs (parameters), perform actions, and return outputs.


Why Use Functions?

  • Reusability: Write once, use multiple times.

  • Modularity: Break complex programs into simpler pieces.

  • Maintainability: Easier to manage and debug.

  • Organization: Makes code more readable.


Function Syntax

Here's the basic structure of a function in C:

returnType functionName(parameterType1 param1, parameterType2 param2) {
    // Function body
    return value;
}
  1. returnType: The type of value the function returns (e.g., int, float, void).

  2. functionName: The name you give the function.

  3. parameterType: The type of input the function takes.

  4. Function body: The code that performs the task.


Example of a Simple Function

Let’s create a function that adds two numbers and returns the result.

#include <stdio.h>

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

int main() {
    int sum = add(5, 10);  // Calling the function with arguments 5 and 10
    printf("Sum: %d\n", sum);  // Outputs: Sum: 15
    return 0;
}

Types of Functions

  1. Functions with No Parameters and No Return Value

    • These functions perform a task but don't take input or return anything.

    Example:

    void sayHello() {
        printf("Hello, World!\n");
    }
    
    int main() {
        sayHello();  // Outputs: Hello, World!
        return 0;
    }
  2. Functions with Parameters but No Return Value

    • These take inputs but don’t return a value.

    Example:

    void printNumber(int num) {
        printf("Number: %d\n", num);
    }
    
    int main() {
        printNumber(100);  // Outputs: Number: 100
        return 0;
    }
  3. Functions with Return Value but No Parameters

    • These return a value but don’t take any inputs.

    Example:

    int getRandomNumber() {
        return 42;
    }
    
    int main() {
        int random = getRandomNumber();
        printf("Random Number: %d\n", random);  // Outputs: Random Number: 42
        return 0;
    }
  4. Functions with Both Parameters and Return Value

    • These take inputs and return a value, like the add function above.


Function Declaration vs. Definition

In C, you can declare a function before you define it. The declaration tells the compiler about the function's name, return type, and parameters, but not the actual implementation. This is useful when you want to define your functions later in the code.

Declaration Example:

int add(int a, int b);  // Declaration (called prototype)

int main() {
    int sum = add(5, 10);
    printf("Sum: %d\n", sum);
    return 0;
}

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

Return Statement

The return statement is used to exit a function and send a value back to the function’s caller.

Example:

int square(int num) {
    return num * num;  // Returns the square of 'num'
}

int main() {
    int result = square(4);
    printf("Square of 4 is: %d\n", result);  // Outputs: Square of 4 is: 16
    return 0;
}

Scope of Variables

  • Local Variables: Variables declared inside a function are local to that function. You cannot access them outside the function.

  • Global Variables: Variables declared outside all functions are global and can be accessed by any function in the program.

Example:

int globalVar = 100;  // Global variable

void printGlobal() {
    printf("Global Variable: %d\n", globalVar);  // Can access 'globalVar'
}

int main() {
    printGlobal();  // Outputs: Global Variable: 100
    return 0;
}

Passing Arguments: Call by Value

In C, arguments are passed to functions by value, meaning the function receives a copy of the variable, not the actual variable itself. Any changes to the parameter inside the function do not affect the original variable.

Example:

void changeValue(int x) {
    x = 100;  // Changes the local copy, not the original
}

int main() {
    int num = 50;
    changeValue(num);
    printf("Value of num: %d\n", num);  // Outputs: Value of num: 50
    return 0;
}

Practical Example: Factorial Function

Let’s create a function that calculates the factorial of a number (n! = n × (n-1) × … × 1).

#include <stdio.h>

// Function to calculate factorial
int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);  // Recursive call
}

int main() {
    int result = factorial(5);  // 5! = 5 * 4 * 3 * 2 * 1 = 120
    printf("Factorial of 5: %d\n", result);  // Outputs: Factorial of 5: 120
    return 0;
}

Summary

  • Functions in C help organize your code and make it reusable.

  • A function has a return type, name, and parameters.

  • You can declare a function before defining it.

  • Functions can take input (parameters) and return output.

  • Variables inside functions are local, while variables outside are global.

PreviousMultidimensional ArraysNextRecursion

Last updated 9 months ago

Was this helpful?