Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Function Declaration and Definition in C

Introduction

Functions are one of the fundamental building blocks in C programming. They allow you to encapsulate code for specific tasks, making your code modular, reusable, and easier to understand. In this tutorial, we will cover the basics of function declaration and definition in C.

Function Declaration

Function declaration, also known as function prototype, tells the compiler about the function name, return type, and parameters. It does not contain the function body.

The syntax for declaring a function is:

return_type function_name(parameter_list);

Here, return_type is the data type of the value the function returns, function_name is the name of the function, and parameter_list is a list of parameters the function takes.

Function Definition

Function definition contains the actual body of the function. It includes the code that specifies what the function does.

The syntax for defining a function is:

return_type function_name(parameter_list) {
    // function body
}

Let's see a complete example of a function declaration and definition:

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

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

Example: Using Functions

Below is an example that demonstrates the use of a declared and defined function in a complete C program:

#include <stdio.h>

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

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

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

In this example, the function add is declared before the main function and defined after it. The main function calls the add function with arguments 5 and 3, and prints the result.

Function Parameters and Return Types

Functions can take zero or more parameters and can return a value. If a function does not return a value, it is declared with a void return type. Similarly, if a function does not take any parameters, its parameter list is specified as void.

Here are some examples:

// Function with no parameters and no return value
void greet() {
    printf("Hello, World!\n");
}

// Function with parameters and no return value
void display(int a) {
    printf("The number is: %d\n", a);
}

// Function with no parameters and a return value
int getNumber() {
    return 42;
}

Conclusion

In this tutorial, we covered the basics of function declaration and definition in C. We discussed the syntax and provided examples to illustrate how functions are declared and defined. Functions are essential for creating modular, maintainable, and reusable code in C programming.