Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of Functions in C:
3.
Function Declaration
4.
Function Definition
5.
Function Calls
6.
Example of C Function
6.1.
C
7.
Function Return Type
7.1.
int
7.2.
float
7.3.
char
7.4.
void
8.
Function Arguments
9.
Examples of function arguments:
9.1.
Single argument
9.2.
C
9.3.
Multiple arguments
9.4.
C
9.5.
Array argument
9.6.
C
10.
Conditions of Return Types & Arguments
10.1.
Conditions for Return Types
10.2.
Conditions for Arguments
11.
Example
11.1.
C
12.
How Does C Function Work?
12.1.
Function Declaration
12.2.
Function Definition
12.3.
Function Call
12.4.
Function Execution
12.5.
Function Return
12.6.
Program Flow
13.
Example
13.1.
C
14.
Types of Functions
14.1.
Library Functions
14.1.1.
Example:
14.2.
C
14.3.
User-Defined Functions
14.3.1.
Example:
14.4.
C
15.
Passing Parameters to Functions:
15.1.
Pass by Value
15.1.1.
Example:
15.2.
C
15.3.
Pass by Reference
15.3.1.
Example:
15.4.
C
16.
Advantages of Functions in C
16.1.
Modularity & Code Reusability
16.2.
Abstraction & Encapsulation
16.3.
Readability & Maintainability
16.4.
Testing & Debugging
16.5.
Code Organization & Collaboration
16.6.
Performance Optimization
16.7.
Recursion
17.
Disadvantages of Functions in C:
17.1.
Function Call Overhead
17.2.
Memory Overhead
17.3.
Parameter Passing Limitations
17.4.
Limited Encapsulation
17.5.
Lack of Overloading
17.6.
Difficulty in Handling Errors
17.7.
Limited Support for Modularity:
18.
Frequently Asked Questions
18.1.
What happens if the number of arguments in a function call doesn't match the declaration?
18.2.
Can a function return more than one value in C?
18.3.
Is it possible to have a function without arguments and return type in C?
19.
Conclusion 
Last Updated: Jun 12, 2024
Easy

Function in C Programming Examples

Author Rinki Deka
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Functions are an essential part of programming in C. They help break down complex problems into smaller, manageable tasks. A function is a block of code that performs a specific task. It takes input, processes it, & returns output. Functions make code more organized, reusable, & easier to debug. 

Function in C Programming Examples

In this article, we will learn about the syntax of functions in C, how to declare & define them, & how to call them. We will also discuss the different types of functions, their advantages, & disadvantages.

Syntax of Functions in C:

The syntax of a function in C consists of two parts: the function declaration & the function definition. The function declaration tells the compiler about the function's name, return type, & parameters. The function definition contains the actual code that the function executes.

Here is the basic syntax of a function in C:

return_type function_name(parameter1, parameter2, ...) {
   // function body
   // statements
   return value;
}

 

  1. return_type: The data type of the value that the function returns. It can be int, float, char, void, or any other data type.
     
  2. function_name: The name of the function. It should be a meaningful name that describes what the function does.
     
  3. parameters: The input values that the function takes. They are optional & are separated by commas.
     
  4. function body: The code that the function executes. It is enclosed in curly braces {}.
     
  5. return value: The value that the function returns. It is optional & depends on the return type of the function.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Function Declaration

A function declaration tells the compiler about the function's name, return type, & parameters. It is also known as the function prototype. The function declaration is usually placed at the top of the program, before the main function.

Here is the syntax of a function declaration:

return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...);


For example, let's say we have a function that takes two integers as input & returns their sum. The function declaration would look like this:

int add(int num1, int num2);


In this example, int is the return type, add is the function name, & num1 & num2 are the parameters of type int.

Note : It's important to note that the function declaration doesn't contain the function body. It just tells the compiler what to expect when the function is called.

Function Definition

The function definition contains the actual code that the function executes. It is the implementation of the function declaration. The function definition consists of the function header & the function body.

Here is the syntax of a function definition:

return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...) {
   // function body
   // statements
   return value;
}


Let's continue with the example of the add function. The function definition would look like this:

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


In this example, the function header is int add(int num1, int num2), & the function body is enclosed in curly braces {}. The function takes two integers num1 & num2 as input, adds them, & stores the result in the variable sum. Finally, the function returns the value of sum using the return statement.

Note : The function definition can be placed anywhere in the program, but it is usually placed after the main function.

Function Calls

To use a function, we need to call it. A function call is a statement that tells the compiler to execute the function. When a function is called, the program control is transferred to the function, & the function executes its code. Once the function is finished, the program control is transferred back to the calling statement.

Here is the syntax of a function call:

function_name(argument1, argument2, ...);


The function_name is the name of the function that we want to call, & the arguments are the values that we pass to the function. The arguments should match the parameters of the function in number, order, & type.

Let's say we have a function add that takes two integers as input & returns their sum. To call this function, we would use the following statement:

int result = add(5, 3);


In this example, we are calling the add function with the arguments 5 & 3. The function will execute its code & return the sum of 5 & 3, which is 8. The returned value is then stored in the variable result.

We can also call a function without storing its return value:

add(5, 3);


In this case, the function will execute its code, but the returned value will be ignored.

Example of C Function

Let's take a look at a complete example of a C function that calculates the area of a rectangle:

  • C

C

#include <stdio.h>

// Function declaration
int calculateArea(int length, int width);

int main() {
int len = 5;
int wid = 3;
int area = calculateArea(len, wid);
printf("The area of the rectangle is: %d\n", area);
return 0;
}

// Function definition
int calculateArea(int length, int width) {
int area = length * width;
return area;
}

Output

The area of the rectangle is: 15


In this example, we have a function calculateArea that takes two integers length & width as input & returns their product, which is the area of the rectangle.

The function declaration int calculateArea(int length, int width); is placed before the main function. It tells the compiler about the function's name, return type, & parameters.

In the main function, we declare two variables len & wid & assign them the values 5 & 3 respectively. We then call the calculateArea function with len & wid as arguments & store the returned value in the variable area. Finally, we print the value of area using the printf function.

The function definition int calculateArea(int length, int width) { ... } is placed after the main function. It contains the actual code that calculates the area of the rectangle. The function takes length & width as input, multiplies them, & stores the result in the variable area. Finally, the function returns the value of area using the return statement.

Function Return Type

The return type of a function specifies the type of value that the function returns. It can be any valid C data type, such as int, float, char, void, etc.

Here are some examples of function return types:

int

The function returns an integer value.

int square(int num) {
   return num * num;
}

float

The function returns a floating-point value.

float calculateAverage(float num1, float num2) {
   return (num1 + num2) / 2;
}

char

The function returns a character value.

char getGrade(int marks) {
   if (marks >= 90) return 'A';
   else if (marks >= 80) return 'B';
   else if (marks >= 70) return 'C';
   else if (marks >= 60) return 'D';
   else return 'F';
}

void

The function doesn't return any value.

void printMessage(char* message) {
   printf("%s\n", message);
}


The void return type is used when the function doesn't need to return a value. It is also used for functions that perform some action, such as printing a message or modifying a global variable.

Note : It's important to choose the appropriate return type for a function based on its purpose & the value it needs to return.

Function Arguments

Function arguments are the values that are passed to a function when it is called. They provide a way to pass data from the calling function to the called function. The arguments are specified in the function declaration & the function call.

Examples of function arguments:

Single argument

  • C

C

#include <iostream>
#include <vector>
#include <algorithm>

int square(int num) {

  return num * num;

}

int main() {

  int result = square(5);

  printf("The square of 5 is: %d\n", result);

  return 0;

}

Output

The square of 5 is: 25


In this example, the square function takes a single argument num of type int. When the function is called with the argument 5, the value of num inside the function is 5.

Multiple arguments

  • C

C

#include <iostream>
#include <vector>
#include <algorithm>

int add(int num1, int num2) {

  return num1 + num2;

}

int main() {

  int result = add(5, 3);

  printf("The sum of 5 and 3 is: %d\n", result);

  return 0;

}

Output

The sum of 5 and 3 is: 8


In this example, the add function takes two arguments num1 & num2 of type int. When the function is called with the arguments 5 & 3, the value of num1 inside the function is 5, & the value of num2 is 3.

Array argument

  • C

C

#include <iostream>
#include <vector>
#include <algorithm>

int sumArray(int arr[], int size) {

  int sum = 0;

  for (int i = 0; i < size; i++) {

     sum += arr[i];

  }

  return sum;

}

int main() {

  int numbers[] = {1, 2, 3, 4, 5};

  int size = sizeof(numbers) / sizeof(numbers[0]);

  int result = sumArray(numbers, size);

  printf("The sum of the array is: %d\n", result);

  return 0;

}

Output

The sum of the array is: 15


In this example, the sumArray function takes an array arr of type int & an integer size as arguments. When the function is called with the arguments numbers & size, the array numbers is passed to the function, & the size of the array is passed as the second argument.

Note : Function arguments allow us to pass data to a function & make the function more flexible & reusable.

Conditions of Return Types & Arguments

When declaring & defining functions in C, there are certain conditions that must be met regarding the return types & arguments. These conditions ensure that the function is used correctly & that the program behaves as expected.

Conditions for Return Types

  1. The return type of a function must be specified in the function declaration & definition.
     
  2. The return type must be a valid C data type, such as int, float, char, void, etc.
     
  3. If the function returns a value, it must use the return statement followed by the value to be returned.
     
  4. If the function doesn't return a value, the return type should be void.
     
  5. The return statement terminates the function execution & returns control to the calling function.

Conditions for Arguments

  1. The arguments of a function must be specified in the function declaration & definition.
     
  2. The arguments must have a valid C data type, such as int, float, char, void, etc.
     
  3. The number & type of arguments in the function call must match the number & type of parameters in the function declaration.
     
  4. If the function doesn't take any arguments, the parameter list should be void or empty.
     
  5. Arrays can be passed as arguments to a function, but they decay to pointers, so the size of the array must be passed as a separate argument.
     
  6. Structs can also be passed as arguments to a function, either by value or by reference using pointers.

Example

  • C

C

#include <stdio.h>

// Function declaration

int multiply(int num1, int num2);

int main() {

  int result = multiply(5, 3);

  printf("The product of 5 and 3 is: %d\n", result);

  return 0;

}

// Function definition

int multiply(int num1, int num2) {

  return num1 * num2;

}

Output

The product of 5 and 3 is: 15

In this example, the multiply function takes two arguments of type int & returns an int value. The function declaration & definition specify the return type & arguments correctly. The function call in main passes the correct number & type of arguments, & the returned value is stored in the result variable.

How Does C Function Work?

C functions work by breaking down a complex problem into smaller, more manageable tasks. Each function performs a specific task & can be called multiple times from different parts of the program. Let’s see how C functions work:

Function Declaration

  1. The function is declared before it is used in the program.
     
  2. The declaration specifies the function's name, return type, & parameters.
     
  3. It tells the compiler what to expect when the function is called.

Function Definition

  1. The function definition contains the actual code that the function executes.
     
  2. It consists of the function header (name, return type, & parameters) & the function body (code block).
     
  3. The function body is enclosed in curly braces {} & contains the statements that perform the function's task.

Function Call

  1. When a function is called, the program control is transferred to the function.
     
  2. The calling statement passes the required arguments to the function.
     
  3. The function executes its code block using the provided arguments.
     
  4. If the function returns a value, it is returned to the calling statement.

Function Execution

  1. The function executes its code block line by line.
     
  2. It performs the specified task using the provided arguments & local variables.
     
  3. The function may call other functions or use control structures like loops & conditionals.
     

If the function encounters a return statement, it terminates & returns control to the calling statement.

Function Return

  1. If the function has a return type other than void, it must return a value using the return statement.
     
  2. The returned value is passed back to the calling statement.
     
  3. The calling statement can store the returned value in a variable or use it directly.

Program Flow

  1. After the function completes its execution, the program control is transferred back to the calling statement.
     
  2. The program continues executing from the point where the function was called.
     
  3. The function call can be part of an expression, a control structure, or a larger block of code.

Example

  • C

C

#include <stdio.h>

// Function declaration

int square(int num);

int main() {

  int result = square(5);

  printf("The square of 5 is: %d\n", result);

  return 0;

}

// Function definition

int square(int num) {

  return num * num;

}

Output

The square root of 5 is: 25


In this example:

  1. The square function is declared before main with the return type int & parameter int num.
     
  2. Inside main, the square function is called with the argument 5, & the returned value is stored in the result variable.
     
  3. The function definition of square specifies the code block that multiplies the parameter num by itself & returns the result.
     
  4. The program control is transferred to the square function, executes its code block, & returns the square of 5 to the calling statement.
     
  5. The main function prints the value of result, which is 25.
     

Note : C functions provide a way to modularize code, make it reusable, & improve the overall structure of the program.

Types of Functions

In C, there are two main types of functions:

  • Library Functions
     
  • User-Defined Functions
     

Let's discuss each type in detail.

Library Functions

  1. Library functions are pre-defined functions provided by the C standard library.
     
  2. They are built-in functions that perform specific tasks & are readily available for use.
     
  3. To use a library function, you need to include the appropriate header file that declares the function.
     
  4. Examples of library functions include printf(), scanf(), strlen(), sqrt(), etc.
     
  5. These functions are optimized & tested for efficiency & reliability.
     

Example:

  • C

C

#include <stdio.h>
#include <math.h>

int main() {
double num = 16.0;
double sqrtResult = sqrt(num);
printf("The square root of %.2lf is %.2lf\n", num, sqrtResult);
return 0;
}
6.00 is 4.00


In this example, the sqrt() function from the math.h library is used to calculate the square root of a number.

User-Defined Functions

  1. User-defined functions are functions created by the programmer to perform specific tasks.
     
  2. These functions are defined by the user based on their program's requirements.
     
  3. User-defined functions can be created to encapsulate a block of code that needs to be reused multiple times.
     
  4. They provide modularity, code reusability, & make the program more organized & readable.
     
  5. The programmer specifies the function name, return type, parameters, & the code block to be executed.
     

Example:

  • C

C

#include <stdio.h>

// User-defined function to calculate the factorial of a number
int factorial(int num) {
if (num == 0 || num == 1) {
return 1;
} else {
return num * factorial(num - 1);
}
}

int main() {
int number = 5;
int result = factorial(number);
printf("The factorial of %d is %d\n", number, result);
return 0;
}

Output

The factorial of 5 is 120


In this example, the user-defined function factorial() is created to calculate the factorial of a number using recursion.

Note : Both library functions & user-defined functions play important roles in C programming. Library functions provide pre-built functionality for common tasks, while user-defined functions allow programmers to create custom functions customised to their specific needs.

Passing Parameters to Functions:

In C, parameters are used to pass values or references to functions. There are two ways to pass parameters to functions:

  • Pass by Value
     
  • Pass by Reference

Let's discuss each method in detail.

Pass by Value

  • In pass by value, a copy of the actual parameter is passed to the function.
     
  • Any changes made to the parameter inside the function do not affect the original value outside the function.
     
  • The function receives a copy of the value & works with it locally.

Example:

  • C

C

#include <stdio.h>

void incrementByValue(int num) {

  num++;

  printf("Inside the function: num = %d\n", num);

}

int main() {

  int number = 5;

  printf("Before function call: number = %d\n", number);

  incrementByValue(number);

  printf("After function call: number = %d\n", number);

  return 0;

}

Output:

Before function call: number = 5
Inside the function: num = 6
After function call: number = 5


In this example, the incrementByValue() function receives a copy of the number variable. The function increments the value of num, but it doesn't affect the original number variable in the main() function.

Pass by Reference

  • In pass by reference, the memory address of the actual parameter is passed to the function.
     
  • Any changes made to the parameter inside the function directly affect the original value outside the function.
     
  • The function receives the memory address of the variable & can modify its value.
     
  • To pass by reference, pointers are used.

Example:

  • C

C

#include <stdio.h>

void incrementByReference(int* num) {

  (*num)++;

  printf("Inside the function: num = %d\n", *num);

}

int main() {

  int number = 5;

  printf("Before function call: number = %d\n", number);

  incrementByReference(&number);

  printf("After function call: number = %d\n", number);

  return 0;

}

Output

Before function call: number = 5
Inside the function: num = 6
After function call: number = 6


In this example, the incrementByReference() function receives the memory address of the number variable using a pointer *num. The function increments the value at that memory address, which directly affects the original number variable in the main() function.

Pass by reference is useful when you want to modify the original value of a variable inside a function or when you need to return multiple values from a function.

Note : It's important to choose the appropriate method based on whether you want to pass a copy of the value or modify the original value.

Advantages of Functions in C

Modularity & Code Reusability

  • Functions allow you to divide a large program into smaller, more manageable parts.
     
  • Each function can be designed to perform a specific task, making the code more modular & easier to understand.
     
  • Functions can be reused multiple times throughout the program, reducing code duplication & improving efficiency.

Abstraction & Encapsulation

  • Functions provide a level of abstraction by hiding the implementation details from the caller.
     
  • The caller only needs to know the function's name, parameters, & return type to use it effectively.
     
  • Encapsulation is achieved by keeping the function's internal workings separate from the rest of the program.

Readability & Maintainability

  • Functions make the code more readable by breaking it down into logical & self-contained units.
     
  • Each function can be given a meaningful name that describes its purpose, making the code more self-explanatory.
     
  • Maintaining & debugging the code becomes easier when it is organized into functions.

Testing & Debugging

  • Functions allow for isolated testing & debugging of individual parts of the program.
     
  • Each function can be tested independently to ensure its correctness before integrating it into the larger program.
     
  • Debugging becomes more efficient as errors can be traced back to specific functions.

Code Organization & Collaboration

  • Functions help in organizing the code into logical & related groups.
     
  • Different programmers can work on different functions simultaneously, promoting collaboration & parallel development.
     
  • Functions can be stored in separate files, making the codebase more manageable & allowing for code sharing & reuse across projects.

Performance Optimization

  • Functions can be optimized individually for better performance.
     
  • Frequently used functions can be made inline to reduce function call overhead.
     
  • Functions can be modified & optimized without affecting the rest of the program.

Recursion

  • Functions enable the implementation of recursive algorithms.
     
  • Recursion allows a function to call itself repeatedly to solve problems that can be divided into smaller subproblems.
     
  • Many complex problems, such as traversing trees or calculating factorials, can be solved elegantly using recursive functions.

Disadvantages of Functions in C:

Function Call Overhead

  • Each time a function is called, there is an overhead associated with it.
     
  • The program needs to jump to the function's location, push arguments onto the stack, & then return back to the calling location.
     
  • If a function is called frequently or if there are many small functions, the function call overhead can impact the program's performance.

Memory Overhead

  • Functions require memory allocation for their parameters, local variables, & return values.
     
  • When a function is called, memory is allocated on the stack for its parameters & local variables.
     
  • If a program has many functions or if functions have large parameter lists or local arrays, it can consume a significant amount of memory.

Parameter Passing Limitations

  • In C, parameters are passed by value by default, meaning that a copy of the value is passed to the function.
     
  • If you need to modify the original value inside the function, you need to pass the parameter by reference using pointers.
     
  • Passing large structures or arrays by value can be inefficient as it involves copying the entire data.

Limited Encapsulation

  • C functions provide a basic level of encapsulation, but it is not as strong as in object-oriented programming languages.
     
  • Functions can access & modify global variables, which can lead to unintended side effects & make the code harder to maintain.
     
  • C lacks features like access modifiers (e.g., private, public) to enforce strict encapsulation.

Lack of Overloading

  • C does not support function overloading, which means you cannot have multiple functions with the same name but different parameters.
     
  • If you need to perform similar operations on different data types, you need to create separate functions with different names.
     
  • This can lead to code duplication & make the code less expressive compared to languages that support function overloading.

Difficulty in Handling Errors

  • C functions typically rely on return values to indicate success or failure.
     
  • If a function encounters an error, it needs to return an error code or set a global error variable.
     
  • This can make error handling more cumbersome & require additional checks in the calling code.

Limited Support for Modularity:

  • While functions help in modularizing the code, C lacks built-in support for creating modules or packages.
     
  • Functions need to be manually organized into separate files & linked together during the build process.
     
  • This can make it harder to achieve true modularity & encapsulation compared to languages with more advanced module systems.

Frequently Asked Questions

What happens if the number of arguments in a function call doesn't match the declaration?

If a function is called with a different number of arguments than it expects, it can lead to compile-time errors. The C compiler checks that the number and types of arguments match during compilation.

Can a function return more than one value in C?

A function in C can return only one value directly. To return multiple values, you can use pointers or return a structure that contains multiple values.

Is it possible to have a function without arguments and return type in C?

Yes, you can define a function with no arguments and a void return type. This type of function performs actions but does not return a value.

Conclusion 

In this article, we discussed the concept of functions in C programming. We learned about the syntax, declaration, definition, & calling of functions. We explained the different aspects of functions, such as return types, parameters, & argument passing. We also saw the two types of functions: library functions & user-defined functions. Apart from all this, we also understood the advantages & disadvantages of using functions in C.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
What happens when a function is called before its declaration in C?
Next article
Noreturn function specifier in C
Live masterclass