Loading...
Loading...

C Functions Tutorial

Functions in C are blocks of code that perform a specific task. This tutorial will guide you through defining, declaring, and calling functions in C, along with examples.

1. What is a Function?

A function is a block of code that performs a specific task, and it can be reused multiple times throughout your program.

2. Function Declaration

Before using a function, it must be declared. The declaration specifies the function's name, return type, and parameters:

#include <stdio.h>

void greet();  // Function declaration

int main() {
    greet();  // Function call
    return 0;
}

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

The greet() function is declared before it is called in the main function.

3. Function Definition

The function definition provides the actual code that will be executed. It consists of the return type, function name, and parameters (if any), followed by the function body:

#include <stdio.h>

void greet() {  // Function definition
    printf("Hello, World!\\n");
}

int main() {
    greet();  // Function call
    return 0;
}

The function greet() is defined after the main function and can be called in the main program.

4. Function with Arguments

Functions can accept arguments (parameters) to work with different data. Here's how to define a function that takes parameters:

#include <stdio.h>

void greet(char name[]) {  // Function with argument
    printf("Hello, %s!\\n", name);
}

int main() {
    greet("John");  // Calling the function with an argument
    return 0;
}

The function greet() now takes an argument, name, which is passed when calling the function in main.

5. Function with Return Value

Functions can also return a value. Here's an example of a function that returns a value:

#include <stdio.h>

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

int main() {
    int result = add(5, 3);  // Function call with return value
    printf("Result: %d\\n", result);
    return 0;
}

The function add() takes two integers as arguments and returns their sum.

6. Conclusion

Functions are powerful tools in C programming. They help you organize your code, increase reusability, and make your programs more modular and maintainable. Practice defining, declaring, and calling functions to master them.

0 Interaction
257 Views
Views
30 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home