The Wayback Machine - https://web.archive.org/web/20241121215130/https://www.geeksforgeeks.org/c-functions/
Open In App

C Functions

Last Updated : 09 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A function in C is a set of statements that when called perform some specific tasks. It is the basic building block of a C program that provides modularity and code reusability. The programming statements of a function are enclosed within { } braces, having certain meanings and performing certain operations. They are also called subroutines or procedures in other languages.

In this article, we will learn about functions, function definition. declaration, arguments and parameters, return values, and many more.

Syntax of Functions in C

The syntax of function can be divided into 3 aspects:

  1. Function Declaration
  2. Function Definition
  3. Function Calls

Function Declarations

In a function declaration, we must provide the function name, its return type, and the number and type of its parameters. A function declaration tells the compiler that there is a function with the given name defined somewhere else in the program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2);

The parameter name is not mandatory while declaring functions. We can also declare the function without using the name of the data variables.

Example

int sum(int a, int b);  // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Declaration

Function Declaration

Note: A function in C must always be declared globally before calling it.

Function Definition

The function definition consists of actual statements which are executed when the function is called (i.e. when the program control comes to the function).

A C function is generally defined and declared in a single step because the function definition always starts with the function declaration so we do not need to declare it explicitly. The below example serves as both a function definition and a declaration.

return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}
Function Defination in C

Function Definition in C

Function Call

A function call is a statement that instructs the compiler to execute the function. We use the function name and parameters in the function call.

In the below example, the first sum function is called and 10,30 are passed to the sum function. After the function call sum of a and b is returned and control is also returned back to the main function of the program.

Working of function in C

Working of function in C

Note: Function call is neccessary to bring the program control to the function definition. If not called, the function statements will not be executed.

Example of C Function

C
// C program to show function
// call and definition
#include <stdio.h>

// Function that takes two parameters 
// a and b as inputs and returns 
// their sum
int sum(int a, int b) 
{ 
  return a + b; 
}

// Driver code
int main()
{
  // Calling sum function and 
  // storing its value in add variable
  int add = sum(10, 30);
  
  printf("Sum is: %d", add);
  return 0;
}

Output
Sum is: 40

As we noticed, we have not used explicit function declaration. We simply defined and called the function.

Function Return Type

Function return type tells what type of value is returned after all function is executed. When we don’t want to return a value, we can use the void data type.

Example:

int func(parameter_1,parameter_2);

The above function will return an integer value after running statements inside the function.

Note: Only one value can be returned from a C function. To return multiple values, we have to use pointers or structures.

Function Arguments

Function Arguments (also known as Function Parameters) are the data that is passed to a function.

Example:

int function_name(int var1, int var2);

Conditions of Return Types and Arguments

In C programming language, functions can be called either with or without arguments and might return values. They may or might not return values to the calling functions.

  1. Function with no arguments and no return value
  2. Function with no arguments and with return value
  3. Function with argument and with no return value
  4. Function with arguments and with return value

To know more about function Arguments and Return values refer to the article – Function Arguments & Return Values in C.

How Does C Function Work?

Working of the C function can be broken into the following steps as mentioned below:

  1. Declaring a function: Declaring a function is a step where we declare a function. Here we specify the return types and parameters of the function.
  2. Defining a function: This is where the function’s body is provided. Here, we specify what the function does, including the operations to be performed when the function is called.
  3. Calling the function: Calling the function is a step where we call the function by passing the arguments in the function.
  4. Executing the function: Executing the function is a step where we can run all the statements inside the function to get the final result.
  5. Returning a value: Returning a value is the step where the calculated value after the execution of the function is returned. Exiting the function is the final step where all the allocated memory to the variables, functions, etc is destroyed before giving full control back to the caller.

Types of Functions

There are two types of functions in C:

  1. Library Functions
  2. User Defined Functions
Types of Functions

Types of Functions in C

1. Library Function

A library function is also referred to as a “built-in function”. A compiler package already exists that contains these functions, each of which has a specific meaning and is included in the package. Built-in functions have the advantage of being directly usable without being defined, whereas user-defined functions must be declared and defined before being used. 

For Example:

pow(), sqrt(), strcmp(), strcpy() etc.

Advantages of C library functions

  • C Library functions are easy to use and optimized for better performance.
  • C library functions save a lot of time i.e, function development time.
  • C library functions are convenient as they always work.

Example:

C
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
  double Number;
  Number = 49;

  // Computing the square root with 
  // the help of predefined C 
  // library function
  double squareRoot = sqrt(Number);
  
  printf("The Square root of %.2lf = %.2lf", 
          Number, squareRoot);
  return 0;
}

Output
The Square root of 49.00 = 7.00

2. User Defined Function

Functions that the programmer creates are known as User-Defined functions or “tailor-made functions”. User-defined functions can be improved and modified according to the need of the programmer. Whenever we write a function that is case-specific and is not defined in any header file, we need to declare and define our own functions according to the syntax.

Advantages of User-Defined Functions

  • Changeable functions can be modified as per need.
  • The Code of these functions is reusable in other programs.
  • These functions are easy to understand, debug and maintain.

Example:

C
// C program to show 
// user-defined functions
#include <stdio.h>

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

// Driver code
int main()
{
  int a = 30, b = 40;
 
  // function call
  int res = sum(a, b);

  printf("Sum is: %d", res);
  return 0;
}

Output
Sum is: 70

Passing Parameters to Functions

The data passed when the function is being invoked is known as the Actual parameters. In the below program, 10 and 30 are known as actual parameters. Formal Parameters are the variable and the data type as mentioned in the function declaration. In the below program, a and b are known as formal parameters.

Passing Parameters to Functions

Passing Parameters to Functions

We can pass arguments to the C function in two ways:

  1. Pass by Value
  2. Pass by Reference

1. Pass by Value

Parameter passing in this method copies values from actual parameters into formal function parameters. As a result, any changes made inside the functions do not reflect in the caller’s parameters. 

Example:

C
// C program to show use 
// of call by value
#include <stdio.h>

void swap(int var1, int var2)
{
  int temp = var1;
  var1 = var2;
  var2 = temp;
}

// Driver code
int main()
{
  int var1 = 3, var2 = 2;
  printf("Before swap Value of var1 and var2 is: %d, %d\n",
          var1, var2);
  swap(var1, var2);
  printf("After swap Value of var1 and var2 is: %d, %d",
          var1, var2);
  return 0;
}

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2

2. Pass by Reference

The caller’s actual parameters and the function’s actual parameters refer to the same locations, so any changes made inside the function are reflected in the caller’s actual parameters. 

Example:

C
// C program to show use of 
// call by Reference
#include <stdio.h>

void swap(int *var1, int *var2)
{
  int temp = *var1;
  *var1 = *var2;
  *var2 = temp;
}

// Driver code
int main()
{
  int var1 = 3, var2 = 2;
  printf("Before swap Value of var1 and var2 is: %d, %d\n",
          var1, var2);
  swap(&var1, &var2);
  printf("After swap Value of var1 and var2 is: %d, %d",
          var1, var2);
  return 0;
}

Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3

Advantages of Functions in C

Functions in C is a highly useful feature of C with many advantages as mentioned below:

  1. The function can reduce the repetition of the same statements in the program.
  2. The function makes code readable by providing modularity to our program.
  3. There is no fixed number of calling functions it can be called as many times as you want.
  4. The function reduces the size of the program.
  5. Once the function is declared you can just use it without thinking about the internal working of the function.

Disadvantages of Functions in C

The following are the major disadvantages of functions in C:

  1. Cannot return multiple values.
  2. Memory and time overhead due to stack frame allocation and transfer of program control.

Conclusion

In this article, we discussed the following points about the function as mentioned below:

  1. The function is the block of code that can be reused as many times as we want inside a program.
  2. To use a function we need to call a function.
  3. Function declaration includes function_name, return type, and parameters.
  4. Function definition includes the body of the function.
  5. The function is of two types user-defined function and library function.
  6. In function, we can according to two types call by value and call by reference according to the values passed.

FAQs on Functions in C

Q1. Define functions.

Answer:

Functions are the block of code that is executed every time they are called during an execution of a program.

Q2. What is a forward declaration?

Answer:

Sometimes we define the function after its call to provide better readibliy. In such cases, we declare function before the their defiinition and call. Such declaration are called Forward Declaration.

Q3. What is the difference between function declaration and definition?

Answer:

The data like function name, return type, and the parameter is included in the function declaration whereas the definition is the body of the function. All these data are shared with the compiler according to their corresponding steps.

Q4. What is the difference between function arguments and parameters?

Answer:

Function parameters are the values declared in a function declaration. Whereas, function arguments are the values that are passed in the function during the function call.

Example:

int func(int x,int y);
func(10,20);

Here, int x and int y are parameters while, 10 and 20 are the arguments passed to the function.

To know more about it, refer to this article – Difference between Arguments and Parameters in C.

Q5. Can we return multiple values from a C Function?

Answer:

No, it is generally not possible to return multiple values from a function. But we can either use pointers to static or heap memory locations to return multiple values or we can put data in the structure and then return the structure.

To know more about it, refer to this article – How to return multiple values from a function in C or C++?

Q6. What is the actual and formal parameter?

Answer:

Formal parameter: The variables declared in the function prototype is known as Formal arguments or parameters.

Actual parameter:  The values that are passed in the function are known as actual arguments or parameters.

 



Previous Article
Next Article

Similar Reads

Thread functions in C/C++
In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow. It is most effective on multiprocessor or multi-core systems where threads can be implemented on a kernel-level for
5 min read
C Program to Display Prime Numbers Between Two Intervals Using Functions
Prime numbers have only 2 factors, 1 and themselves. For example, 2,3, 5, 7, 9,... are the first 5 prime numbers. Here we will build a C program to display prime numbers between two intervals using functions using 2 approaches, for loop and while loop. Example Input: num1 = 2, num2 = 10 Output: Prime numbers between 2 and 10 are: 2 3 5 7 Explanatio
3 min read
C Library Functions
The Standard Function Library in C is a huge library of sub-libraries, each of which contains the code for several functions. In order to make use of these libraries, link each library in the broader library through the use of header files. The actual definitions of these functions are stored in separate library files, and declarations in header fi
10 min read
Linked List in C
A linked list is a linear data structure where each element, known as a node, is connected to the next one using pointers. Unlike array, elements of linked list are stored in random memory locations. In this article, we will learn about the linked list, its types, representation of the linked list in C, and discuss what link list offers as compared
8 min read
How to Create a Linked List in C?
Write a C program to create a linked list. A linked list is a sequential data structure that stores the data in non-contiguous memory locations unlike array. In a linked list, each element is referred to as a node. Each node in the linked list stores data and a pointer to the next node present in the list. Example Input: 1 -> 2 -> 3 -> 4 -
5 min read
C Exercises - Practice Questions with Solutions for C Programming
The best way to learn C programming language is by hands-on practice. This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more. So, Keep it Up! Solve topic-wise C exercise questions to streng
12 min read
Quick Sort in C
QuickSort is one of the best sorting algorithms that follows the divide-and-conquer approach like Merge Sort but unlike Merge Sort, this algorithm does in place sorting. In this article, we will learn how to implement quicksort in C language. What is QuickSort Algorithm?The basic idea behind QuickSort is to select a pivot element from the array and
4 min read
Reverse String in C
In C, reversing a string means rearranging the characters such that the last character becomes the first, the second-to-last character becomes the second, and so on. For example, Input: S = "hello"Output: "olleh"Explanation: The reverse of "hello" is "olleh". Input: S = "world"Output: "dlrow"Explanation: The reverse of "world" is "dlrow". Program t
4 min read
rand() in C
The rand() function in the C programming language is used to generate pseudo-random numbers. It is used in C to generate random numbers in the range 0 to RAND_MAX. The rand() function is part of the standard C library <stdlib.h> so to use this function, we need to include the <stdlib.h> library. Syntax of rand()int rand(void)ParametersT
3 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Program For Bubble Sort
Bubble Sort is a comparison based simple sorting algorithm that works by comparing the adjacent elements and swapping them if the elements are not in the correct order. It is an in-place and stable sorting algorithm that can sort items in data structures such as arrays and linked lists. In this article, we will learn how to implement bubble sort al
4 min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
C Functions
A function in C is a set of statements that when called perform some specific tasks. It is the basic building block of a C program that provides modularity and code reusability. The programming statements of a function are enclosed within { } braces, having certain meanings and performing certain operations. They are also called subroutines or proc
10 min read
C Program to Make a Simple Calculator
A simple calculator is a program that can perform addition, subtraction, multiplication, and division of two numbers provided as input. In this article, we will learn to create a simple calculator program in C. Example Input: a = 10, b = 5, op = +Output: 15.00Explanation: Chosen operation is addition, so 10 + 5 = 15 Input: a = 12, b = 3, op = /Outp
3 min read
Matrix Multiplication in C
A matrix is a collection of numbers organized in rows and columns, represented by a two-dimensional array in C. Matrices can either be square or rectangular. In this article, we will learn the multiplication of two matrices in the C programming language. ExampleInput: mat1[][] = {{1, 2}, {3, 4}} mat2[][] = {{5, 6}, {7, 8}} Multiplication of two mat
3 min read
Macros and its types in C
In C, a macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;). Examples of Macros in CBelow are the programs to il
6 min read
C Program to Sort an Array in Ascending Order
Sorting an array in ascending order means arranging the elements in the order from smallest element to largest element. The easiest way to sort an array in C is by using qsort() function. This function needs a comparator to know how to compare the values of the array. Let's look at a simple example: [GFGTABS] C #include <stdio.h> #include
3 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Arrow operator -> in C/C++ with Examples
An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: (pointer_name)->(variable_name) Operation: The -> operator in C or C++ gives the val
4 min read
GDB (Step by Step Introduction)
GDB stands for GNU Project Debugger and is a powerful debugging tool for C (along with other languages like C++). It helps you to poke around inside your C programs while they are executing and also allows you to see what exactly happens when your program crashes. GDB operates on executable files which are binary files produced by the compilation p
5 min read
C program to Find the Largest Number Among Three Numbers
Given 3 integer numbers, the task is to find the largest number among them. Examples Input: a = 10, b = 22, c = 19Output: 22 is the largest number.Explanation: Among the numbers 5, 8, and 3, the largest number is 8.Input: a = 12, b = 7, c = 9Output: 12 is the largest number.Explanation: Among the numbers 12, 7, and 9, the largest number is 12. Find
5 min read
C Program to Add Two Integers
Given two integers, the task is to add these integer numbers and return their sum. Examples Input: a = 5, b = 3Output: 8Explanation: The sum of 5 and 3 is 8. Input: a = -2, b = 7Output: 5Explanation: The sum of -2 and 7 is 5. Add Two Numbers in CIn C, we can add two numbers easily using addition operator (+). This operator works by taking two opera
4 min read
Prime Number Program in C
A prime number is a natural number greater than 1 and is completely divisible only by 1 and itself. In this article, we will learn how to check whether the given number is a prime number or not in C. Examples Input: n = 29Output: 29 is primeExplanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number. Input: n = 15Output:
3 min read
C Program for Linear Search
Linear Search is a sequential searching algorithm in C that is used to find an element in a list. Linear Search compares each element of the list with the key till the element is found or we reach the end of the list. Example Input: arr = {10, 50, 30, 70, 80, 60, 20, 90, 40}, key: 30Output: Key Found at Index: 2Explanation: Start from index 0, comp
4 min read
C Program to Check for Palindrome String
A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. Example Input: str = "madam"Output: "madam" is palindrome.Explanation: The reverse of "madam" is "madam". So, it is palindrome Input: str = "hello"Output
5 min read
Factorial Program in C
Write a C program to find the factorial of the given number. A factorial is the product of all the natural numbers less than or equal to the given number N. Examples Input: N = 5Output: 120Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120 Input: N = 0Output: 1Explanation: 0! = 1 by definition Different Ways to Find the Factorial of a Number in CThe logic o
4 min read
C Program to Swap Two Numbers
Swapping two numbers means exchanging their values. In this article, we will learn how to swap values of two numbers in a C program. Example Input: a = 5, b = 10Output: a = 10, b = 5 Input: a = 51, b = 17Output: a = 17, b = 51 Swap Two Numbers Using Temporary VariableThe easiest method to swap two numbers is to use a temporary variable. First, we a
3 min read
C Program for Merge Sort
Merge Sort is a comparison-based sorting algorithm that works by dividing the input array into two halves, then calling itself for these two halves, and finally it merges the two sorted halves. In this article, we will learn how to implement merge sort in C language. What is Merge Sort Algorithm?Merge sort is based on the three principles: divide,
3 min read
C Program For Insertion Sort
Insertion sort is a simple sorting algorithm used to sort a collection of elements in a given order. It is less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort but it is simple to implement and is suitable to sort small data lists. In this article, we will learn about the insertion sort, how it work
4 min read
C Program to Print Fibonacci Series
The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers are 0 and 1 which are used to generate the whole series. Example Input: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3. Input: N = 7Output: 0 1 1 2 3 5 8Explanation: The
4 min read
Article Tags :
three90RightbarBannerImg