Functions in C

nelavalli satheesh
2 min readMay 23, 2021

Functions in C, A function is a block of code that performs a specific task.

There are two types of function in C programming:

1. Standard library functions:

The standard library functions are built-in functions in C programming. ex : printf, scanf etc

2. User-defined functions:

You can also create functions as per your need. Such functions created by the user are known as user-defined functions.

#include<stdio.h>
int add(int, int); // Declaring function
int add(int a, int b) { // definition of function
return a+b;
}
int main() {
int c;
c = add(10,20); // Function call
printf("%d \n",c);
return 0;
}
Output:
30

Advantages of user-defined function

  1. To implement user-defined functions the program will be easier to understand, maintain and debug.
  2. We can Reuse the code in other programs.
  3. A large program can be divided into smaller modules.

In functions two types of arguments 1. call by value 2. call by reference.

call by value won’t affect any changes in that function won’t reflect on the calling function. The example of call by value is above code.

call by reference will affect any changes in that function will reflect on the calling function. For example

#include<stdio.h>void add(int a, int b, int *z) {  // z is call by reference value
*z = a+b; // a and b call by value
}
int main() {
int c;
add(10,20,&c);
printf("%d \n",c);
return 0;
}
Output:
30

Returning value from a function:

  1. return statement:

It returns only one value at a time.

2. Using arguments(out param):

By using this method we can return multiple values at a time.

The parameters through which the called function returns the value to its calling function is called ‘out param’.

The values are which go to function and not returns back are called ‘in param’.

#include <stdio.h>
void add_sub(int a, int b, int *p, int *q){
*p = a+b;
*q = a-b;
}
int main()
{
int x = 20, y=10, sum, diff;
add_sub(x,y,&sum,&diff);
printf("sum:%d diff:%d \n", sum,diff);
return 0;
}
OutPut:
sum:30 diff:10

For more information click here

--

--