View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Functions in C

Updated on 12/02/20253,964 Views

Functions in C programming are blocks of code designed to perform specific tasks. While writing complex programs, repeating code becomes inefficient and error-prone.

Understanding the ins and outs of function calling, argument passing, and return types in C helps you structure your code more effectively and improves efficiency.

This tutorial will equip you with the know-how of functions in C with examples, sharpening your coding skills. Let’s dive into the details!

Boost your C programming skills with our Software Development courses — take the next step in your learning journey!

Aspects of a Function

Functions in C programming allow you to divide your code into smaller, manageable parts, making it easier to maintain and debug. The compiler uses functions to organize the code during the compilation process, ensuring that each part is executed in the right order.

Let's break down the key aspects of functions in C with examples and see how each part fits together.

A function in C consists of several important components:

  1. Return TypeThe return type specifies what kind of value the function will return. It can be any valid C data type, such as int, float, char, or void (if no value is returned).
  2. Function NameThe function name is how the function will be referenced in your code. It should be descriptive of what the function does. Functions in C programming follow the same naming rules as variables.
  3. Parameters (Arguments)Parameters (or arguments) are values passed to the function. You can pass data to a function via parameters, and the function can use them to perform its task. A function may take no parameters, one parameter, or multiple parameters.
  4. Function BodyThe body of the function contains the code that defines what the function does. This is where you put the logic that will execute when the function is called.

Syntax Overview

Here's the basic syntax structure of a function in C:

return_type function_name(parameter1, parameter2, ...)
{
// Function body
// Perform the desired action and return a value if applicable
return value; // optional, depending on the return type
}

Now, let’s look at an example that demonstrates each aspect of a function in action:

Example: Calculating the Area of a Rectangle

#include <stdio.h>
// Function declaration
float calculateArea(float length, float width); // Function prototype
int main() {
// Variables for length and width
float length = 5.5;
float width = 3.2;
// Function call
float area = calculateArea(length, width); // Calling the function
// Output the result
printf("The area of the rectangle is: %.2f\n", area); // Print the result
return 0;
}
// Function definition
float calculateArea(float length, float width) {
// Function body: Calculating the area
return length * width; // Return the calculated area
}

Output:

The area of the rectangle is: 17.60

Explanation:

  1. Return Type:The return type of the function is float, as we want the result (area) to be a floating-point number.
  2. Function Name:The function is named calculateArea, which is descriptive of its purpose – calculating the area of a rectangle.
  3. Parameters:The function takes two parameters: length and width. These represent the dimensions of the rectangle. Both parameters are of type float.
  4. Function Body:The body of the function contains the logic for calculating the area. It multiplies the length by the width and returns the result.
  5. Function Call:In the main function, we call calculateArea(length, width), passing the length and width as arguments. The returned value is stored in the area variable.
  6. Return Statement:In the function definition, the return statement sends the calculated area back to the caller (the main function).

Once you understand these elements, it's important to know where to define a function in your code. The location of function definitions plays a critical role in organizing your program and ensuring its scalability.

Where Should a Function Be Defined?

Functions can be defined in source files (.c) or header files (.h), depending on how you want to organize and use them across your program.

Let’s break down the two primary locations for defining functions:

1. Defining Functions in Source Files

The most common place to define functions is directly in source files (.c). You’ll typically define functions in the source file where they are used. This is the simplest approach, especially for smaller programs, as it keeps the logic of the function and its usage within the same file.

Why is this useful?

  • Encapsulation: The function's logic is contained in one place.
  • Simple structure: Ideal for programs where functions aren’t used across multiple files.

Example:

#include <stdio.h>
// Function definition in the source file
int add(int a, int b) {
return a + b;
}
int main() {
printf("Sum: %d\n", add(5, 3)); // Function call
return 0;
}

Explanation:

  • The add() function is defined directly in the source file and used within main().
  • There's no need for header files if this function is only used within this file.

2. Defining Functions in Header Files

If you plan to use a function across multiple source files, you can declare the function prototype in a header file (.h). The actual definition of the function, however, should still reside in the source file (.c). This practice allows you to share function declarations among different source files.

Why is this useful?

  • Reusability: Functions can be accessed across multiple files.
  • Modularity: Code is organized and modular, making it easier to maintain and update.

Example:

Function prototype in the header file (math_functions.h):

// math_functions.h
int add(int a, int b); // Function prototype

Function definition in the source file (math_functions.c):

#include "math_functions.h"
// Function definition in source file
int add(int a, int b) {
return a + b;
}

Using the function in the main file (main.c):

#include <stdio.h>
#include "math_functions.h" // Include header file for function prototype
int main() {
printf("Sum: %d\n", add(5, 3)); // Function call
return 0;
}

Explanation:

  • The function prototype int add(int a, int b); is declared in the header file (math_functions.h), making it available to other source files like main.c.
  • The definition of the add() function is kept in the source file (math_functions.c), ensuring modularity and reusability.

Understanding these aspects is key to writing well-structured functions.

But what happens if you attempt to use a function before it’s declared? Let’s explore this important aspect next.

What Happens if You Call a Function Before Its Declaration in C?

If you call a function before its declaration, the compiler will produce an error since it doesn’t know the function's details. Here's an example to demonstrate the issue:

#include <stdio.h>
int main() {
printf("Sum: %d", add(5, 3)); // Error: add() function is called before declaration
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}

Error:

error: 'add' undeclared

You can fix this by using a forward declaration to inform the compiler of the function's signature.

Example:

#include <stdio.h>
// Forward declaration
int add(int, int);
int main() {
printf("Sum: %d", add(5, 3));
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}

Output:

Sum: 8

Explanation:

  • The forward declaration (int add(int, int);) informs the compiler about the add function before it’s used in main().
  • Without this declaration, the compiler would generate an error because it would not know the function's details before its call.

Also Read: Compiler vs Interpreter: Difference Between Compiler and Interpreter

Now that you’re clear on the essentials, let’s look at the types of functions in C programming.

Types of Functions in C

There are 2 types of functions in C: Library Functions and User-defined Functions. Both types serve different purposes and offer flexibility depending on the task at hand.

Library Functions:

Library functions are pre-defined functions that come with the C Standard Library. They are ready-to-use functions that perform a specific task, such as mathematical operations, input/output operations, and string manipulation.

Some important library functions include:

  • printf(): Used to print formatted output.
  • scanf(): Used to take formatted input.
  • math.h functions: For example, sqrt(), pow(), and abs().
  • string.h functions: For example, strcpy(), strlen(), and strcmp().

User-defined Functions:

User-defined functions are functions that you define yourself. These functions allow you to break down your code into modular pieces, making it easier to manage, test, and reuse.

Key Points for User-defined Functions:

  • Function Declaration: Declaring the function signature before its definition.
  • Function Definition: Providing the actual implementation of the function.
  • Function Call: Invoking the function from the main() function or any other function.

Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025

Now that we've covered the function structure, let's move on to understanding return types and arguments, which are essential for defining the behavior of your functions.

Conditions of Return Types and Arguments

In C, functions can vary in terms of their arguments and return types. The return type indicates what kind of data the function returns (if any), while arguments are the inputs the function accepts.

Functions can be classified into four major categories based on these conditions.

1. Function with No Arguments and No Return Value

This type of function does not accept any parameters and does not return any value. It is often used for tasks that perform actions without needing inputs or outputs.

Let’s look at an example:

#include <stdio.h>
// Function with no arguments and no return value
void displayMessage() {
printf("Hello, this is a simple function!\n");
}
int main() {
displayMessage(); // Call the function
return 0;
}

Output:

Hello, this is a simple function!

Explanation:

  • Function Declaration: void displayMessage() means no input arguments and no return value.
  • Inside the Function: The function simply prints a message when called.
  • Usage: This type of function is ideal for performing actions like printing messages or displaying status updates without any need for input or output values.

2. Function with No Arguments and With Return Value

This type of function does not take any parameters but returns a value of a specified type. It can be used for calculations or fetching data where no input is required.

Example:

#include <stdio.h>
// Function with no arguments and with return value
int getNumber() {
return 42; // Return a fixed number
}
int main() {
int num = getNumber(); // Call the function and store the return value
printf("Returned value: %d\n", num);
return 0;
}

Output:

Returned value: 42

Explanation:

  • Function Declaration: int getNumber() defines a function that returns an integer.
  • Return Statement: return 42; returns the number 42 when the function is called.
  • Usage: This function is used when you want to retrieve a value without needing any input, like fetching a constant value.

3. Function with Arguments and No Return Value

This function takes parameters but does not return a value. It is useful for operations like modifying data or printing results based on input arguments.

Example:

#include <stdio.h>
// Function with arguments and no return value
void printSquare(int number) {
printf("Square of %d is %d\n", number, number * number);
}
int main() {
printSquare(5); // Call the function with argument
return 0;
}

Output:

Square of 5 is 25

Explanation:

  • Function Declaration: void printSquare(int number) takes one integer argument and doesn't return any value.
  • Function Behavior: It calculates the square of the input number and prints it.
  • Usage: This type of function is useful when you need to perform operations using input data but don’t need to return anything, such as printing or modifying variables.

4. Function with Arguments and With Return Value

This type of function accepts arguments and returns a value, making it suitable for operations like mathematical calculations or any scenario where the function needs input and produces output.

Example:

#include <stdio.h>
// Function with arguments and with return value
int add(int a, int b) {
return a + b; // Return the sum of two numbers
}
int main() {
int sum = add(10, 20); // Call the function with two arguments
printf("Sum: %d\n", sum);
return 0;
}

Output:

Sum: 30

Explanation:

  • Function Declaration: int add(int a, int b) specifies that two integer arguments are passed and an integer is returned.
  • Return Statement: return a + b; returns the sum of the two input values.
  • Usage: This function is useful for performing calculations, where inputs are provided and a result is returned.

Also Read: Command Line Arguments in C Explained

Now that we've grasped return types and arguments, let's explore how to pass parameters to functions and make them even more flexible and dynamic!

Passing Parameters to Functions in C

The data provided when calling a function is referred to as the Actual Parameters. In the example below, 10 and 30 are the actual parameters.

Formal Parameters, on the other hand, are the variables and their data types specified in the function declaration. In this case, a and b are the formal parameters.

In C, functions can receive parameters in two ways: pass by value and pass by reference.

Let’s break them down and see how they work with examples.

Pass by Value

When you pass a variable by value, a copy of the actual value is passed to the function. The function works with this copy, and any changes made inside the function do not affect the original variable.

Let’s look at an example:

#include <stdio.h>
void addTen(int num) {
num = num + 10; // This modifies the local copy of 'num'
printf("Inside function: %d\n", num); // Prints modified value
}
int main() {
int number = 5;
printf("Before function: %d\n", number); // Prints original value
addTen(number); // Pass by value, original 'number' remains unchanged
printf("After function: %d\n", number); // Prints original value again
return 0;
}

Output:

Before function: 5Inside function: 15After function: 5

Explanation:

  • Pass by Value: The original value of the number is passed to the addTen() function. However, since it's a copy, the function does not alter the original number in the main() function.
  • Function Behavior: Inside the function, the value of num is changed, but the original variable remains unaffected.

Pass by Reference

In pass by reference, the memory address of the variable is passed to the function. Any changes made in the function will directly affect the original variable.

Let’s look at an example:

#include <stdio.h>
void addTen(int* num) {
*num = *num + 10; // Dereference the pointer and modify the actual value
printf("Inside function: %d\n", *num); // Prints modified value
}

int main() {
int number = 5;
printf("Before function: %d\n", number); // Prints original value
addTen(&number); // Pass by reference, changes the original 'number'
printf("After function: %d\n", number); // Prints modified value
return 0;
}

Output:

Before function: 5Inside function: 15After function: 15

Explanation:

  • Pass by Reference: The memory address of the number is passed to the addTen() function. Inside the function, the value at that address is modified, which alters the original variable in main().
  • Function Behavior: Since we pass the variable’s memory address, modifications inside the function affect the original value.

Try both pass-by-value and pass-by-reference to get a better grasp on how C handles data. The more you explore, the clearer these concepts will become!

How Well Do You Know Functions in C? 10 MCQs

This quiz will challenge your understanding of functions in C programming. From the basics of defining functions to more advanced concepts like parameter passing and return types, let's see how well you truly know this vital C programming feature!

1. Which of the following is true about functions in C?

A) Functions in C always return a value.

B) Functions can return only integer values.

C) A function can have no return value.

D) Functions can’t take parameters.

2. What is the purpose of a return type in a function in C?

A) To specify what type of argument the function will take.

B) To specify the data type of the value the function will return.

C) To specify the number of times the function will be called.

D) To define the function name.

3. Which of the following function calls is valid in C?

A) func(int a = 5)

B) func(int a, float b)

C) func(int a, b)

D) func(float a, float b = 5)

4. What happens if you don’t use a return statement in a function that is supposed to return a value?

A) The function will return 0 by default.

B) The function will compile without error.

C) The program will result in undefined behavior.

D) The program will terminate.

5. What is the result of calling a function with more parameters than declared?

A) The program will ignore the extra parameters.

B) The compiler will throw an error.

C) The function will use default values for the extra parameters.

D) The extra parameters will be ignored at runtime.

6. How can you pass an array to a function in C?

A) By passing its size

B) By passing a pointer to the array

C) By passing each element of the array individually

D) By passing a copy of the array

7. Which of the following is true about function overloading in C?

A) C allows function overloading directly.

B) Function overloading is achieved by giving functions different names.

C) Function overloading is not supported in C.

D) Function overloading can be done by changing the return type.

8. What does passing by reference allow in function calls in C?

A) It makes the function call faster.

B) It allows the function to modify the value of the original variable.

C) It allows the function to return multiple values.

D) It automatically allocates memory for the variables.

9. In C, which of the following is true about recursive functions?

A) A recursive function must always return a value.

B) Recursive functions can call themselves.

C) Recursive functions don’t need base cases.

D) A recursive function cannot modify global variables.

10. What is the significance of the void return type in a function?

A) It allows the function to return a value of any type.

B) It means the function returns a pointer.

C) It indicates that the function does not return any value.

D) It is used for functions that have infinite loops.

Understanding stack in C is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.

How Can upGrad Help You Master Functions in C?

Now that you've tested your knowledge of functions in C programming, it's time to take your skills to the next level. Upgrading your knowledge is crucial, and upGrad offers in-depth courses designed to enhance your understanding of C programming.

Explore functions in C with examples and more advanced topics like recursion, passing parameters by reference, and memory management in C. upGrad provides a comprehensive learning experience, combining theoretical knowledge with hands-on practice.

Check out upGrad’s programs to advance your knowledge:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!

Similar Reads:

Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Find Out About Data Structures in C and How to Use Them?

FAQs

1. What are the different return types in C functions?

A. In C, return types can be void (no return value), or any data type such as int, float, char, etc.

2. Can functions in C programming have no arguments and return a value?

A. Yes, you can create many types of functions in C programming with no arguments and a return type, like a function that returns a constant or a calculated value.

3. How do function arguments affect the execution of a C program?

A. Arguments allow functions in C programming to process different values, enabling code reuse and flexible functionality by passing different data.

4. What is the difference between pass-by-value and pass-by-reference in C?

A. Pass-by-value sends a copy of the variable's value, while pass-by-reference passes the actual memory address, allowing modification of the original variable.

5. Why should I use void as a return type in C?

A. Use void when a function doesn't need to return a value, indicating that the function performs a task without producing a result.

6. Can I use multiple parameters in C functions?

A. Yes, you can pass multiple parameters of different data types in C functions to process more complex data.

7. How do I handle functions that modify data in C?

A. Use pass-by-reference for modifying data inside functions, as it allows the function to change the original value passed to it.

8. How does recursion work in C functions?

A. Recursion allows a function to call itself. It's useful for solving problems that can be broken down into smaller, similar problems.

9. Can functions in C programming return arrays?

A. No, since you can't return arrays in C, you can return a pointer to the array or use dynamic memory allocation.

10. When should I use functions with return types versus void?

A. Use return types when you need to send back a calculated result, and void when the function just performs an action without returning anything.

11. Can I pass structures as arguments in C functions?

A. Yes, structures can be passed to functions either by value or by reference, enabling functions to manipulate or return complex data structures.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.