🛠️ C Function Basics: Declaration, Definition, and Calling

🛠️ Function Declaration, Definition, and Calling in C

Functions in C allow you to divide your code into small, reusable blocks. This helps you avoid repetition, organize code better, and make your programs easier to read and maintain.


🔰 What is a Function?

A function is a block of code that performs a specific task. C has both built-in functions (like printf()) and user-defined functions (functions you create yourself).


🧱 Parts of a Function

A function typically has 3 main components:

  1. Declaration (or Prototype): Tells the compiler about the function name, return type, and parameters.
  2. Definition: Contains the actual code or logic inside the function.
  3. Calling: Executes the function from main() or another function.

📌 1. Function Declaration (Prototype)

return_type function_name(parameter_list);

This line tells the compiler that the function exists, even before its definition.

🔍 Example:

int add(int, int);

📌 2. Function Definition


return_type function_name(parameter_list) {
    // Function body
}

🔍 Example:


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

📌 3. Function Calling

function_name(arguments);

🔍 Example:


int result = add(5, 3);

✅ Complete Example: Add Two Numbers Using Function


#include <stdio.h>

// Function declaration
int add(int, int);

int main() {
    int num1, num2, sum;
    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    // Function call
    sum = add(num1, num2);

    printf("Sum = %d\n", sum);
    return 0;
}

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

đŸŽ¯ Why Use Functions?

  • 👉 Code reuse: Write once, use multiple times
  • 👉 Better readability and structure
  • 👉 Easy debugging and testing
  • 👉 Modular design: Break complex tasks into small parts

🧠 Function Types in C

Based on return value and parameters:

  1. With return, with parameters
  2. With return, without parameters
  3. Without return, with parameters
  4. Without return, without parameters

🔹 Example: Without return, without parameters


void greet() {
    printf("Hello, welcome!\n");
}

🔹 Example: With return, no parameters


int getNumber() {
    return 42;
}

⚠️ Common Mistakes to Avoid

  • ❌ Using a function before declaring or defining it
  • ❌ Mismatching return types or parameters
  • ❌ Forgetting to return a value in non-void functions

🧩 Practice Problems

  1. Create a function that checks whether a number is even or odd.
  2. Write a function to calculate factorial of a number.
  3. Create a function to find the maximum of three numbers.
  4. Make a function that converts Celsius to Fahrenheit.

function in c, c programming function, function declaration, function definition, function calling, user defined function in c, c programming tutorial, beginners function example in c, how to write a function in c

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ