C Functions

A function in C is a block of code that performs a specific task. Functions allow you to modularize your code and make it more organized and reusable.

Here's an example code snippet that shows how to define and call a function in C:

#include <stdio.h>

int add(int num1, int num2) {
    return num1 + num2;
}

int main() {
    int result = add(10, 20);
    printf("The sum of 10 and 20 is: %d", result);

    return 0;
}

Let's go over this code line by line:

  • We first include the standard input/output library stdio.h.
  • We define a function called add that takes two integer arguments num1 and num2 and returns their sum using the + operator.
  • In the main() function, we call the add function with arguments 10 and 20 and store the result in a variable called result.
  • We use the printf() function to print the value of result using the %d format specifier.
  • Finally, we return 0 to indicate successful execution of the program.

When you run this program, it will print the following output:

The sum of 10 and 20 is: 30

Note that you can also declare and define functions in separate files and use them in your main program using header files. You can also pass arguments by reference to functions using pointers and modify the original values of variables passed to the function. Functions are an important part of C programming and are used extensively in most programs.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

30911