top

Search

C Tutorial

.

UpGrad

C Tutorial

User Defined Functions in C

Introduction

User defined functions in C allow programmers to create custom code blocks for performing specific actions. They consist of function declarations, definitions, and calls, providing a blueprint for the function, while definitions contain the actual code. User-defined functions simplify testing, debugging, and code maintenance by encapsulating logic into modular blocks. 

Advantages of User Defined Functions

In order to further understand the user-defined functions in C, let’s understand its advantages - 

  • Functions provide code reusability, reducing the need to write repetitive code and improving overall code efficiency, saving time and enhancing code readability.

  • Using functions, we can employ the divide and conquer approach, breaking down complex tasks into smaller, manageable sub-tasks. 

  • Functions allow us to abstract implementation details. For example, in C, functions provided by libraries, such as math.h (e.g., pow, sqrt) can be utilised without understanding their underlying implementation. 

  • Functions can be developed once and reused across multiple programs with minimal or no modifications. 

Types of User-defined Functions in C

There are four types of user-defined functions in C. Let’s study what they are with some examples - 

1. Function with No Return Value and without Argument:

This type of function does not return any value and does not require any arguments.

#include <stdio.h>

// Function declaration
void greet();

int main() {
    greet(); // Function call
    return 0;
}

// Function definition
void greet() {
    printf("Hello, world!\n");
}

Output:

Hello, world!

In this example, the greet function is defined without a return type (void) and any arguments. It simply prints "Hello, world!" to the console. The greet function is called from the main function, resulting in the greeting being displayed.

2. Function with No Return Value and with Arguments:

This type of function does not return any value but requires one or more arguments.

#include <stdio.h>

// Function declaration
void addNumbers(int a, int b);

int main() {
    int num1 = 5, num2 = 3;
    addNumbers(num1, num2); // Function call
    return 0;
}

// Function definition
void addNumbers(int a, int b) {
    int sum = a + b;
    printf("Sum: %d\n", sum);
}

Output: 

Sum: 8

In this example, the addNumbers function is defined without a return type (void) but with two integer arguments (a and b). The function calculates the sum of the two numbers and displays the result. The function is called from the main function with num1 and num2 as arguments, resulting in the sum being printed.

3. Function with a Return Value and without Any Argument:

This type of function returns a value but does not require any arguments.

#include <stdio.h>

// Function declaration
int getRandomNumber();

int main() {
    int randomNumber = getRandomNumber(); // Function call
    printf("Random Number: %d\n", randomNumber);
    return 0;
}
// Function definition
int getRandomNumber() {
    return rand() % 100; // Generate a random number between 0 and 99
}

Output:

Random Number: <randomly generated number>

In this example, the getRandomNumber function is defined with an integer return type. The function generates a random number between 0 and 99 using the rand function and returns it. The getRandomNumber function is called from the main function, and the returned random number is printed.

4. Function with a Return Value and with an Argument:

This type of function returns a value and requires one or more arguments.

#include <stdio.h>

// Function declaration
int findMax(int a, int b);

int main() {
    int num1 = 7, num2 = 4;
    int maxNumber = findMax(num1, num2); // Function call
    printf("Maximum Number: %d\n", maxNumber);
    return 0;
}

// Function definition
int findMax(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

Output:

Maximum Number: 7

In this example, the findMax function is defined with an integer return type and two integer arguments (a and b). The function compares the two numbers and returns the maximum of the two. The findMax function is called from the main function with num1 and num2 as arguments, and the returned maximum number is printed.

Elements of User-defined Function in C

Functions in the C language have three essential parts: 

  • Function Declaration

  • Function Definition

  • Function Call

Function Call:

A function call invokes or executes a function in the program. It involves using the function name followed by parentheses, which may contain arguments (values or variables) to be passed to the function.

For example,

int area = getRectangleArea(5, 8);

In this example, the getRectangleArea function is called with arguments 5 and 8, and the returned value is stored in the area variable.

Function declaration

A function declaration serves as a prototype for the function and provides information to the compiler about the user-defined function that may be used later in the code. It includes the function name, return type, and parameters (optional).

Syntax of function declaration

The function declaration syntax is as follows:

returnType functionName(type1 parameter1, type2 parameter2, ...);

The return type indicates the data type returned by the function. The function name is a unique identifier for the function. Parameters specify the number and types of inputs the function accepts.

For example,

int getRectangleArea(int length, int breadth);

Function Definition

A function definition in C contains the actual block of code executed when the function is called. It consists of several components that define the behaviour of the function.

Here are the different components of function definition - 

Return Type:

The return type specifies the value's data type the function will return after its execution. It can be any valid C data type, such as int, float, char, void, etc. If the function does not return a value, the return type is specified as void.

Function Name:

The function name is a unique identifier for the function. It calls or invokes the function from other parts of the program. The function name should follow the rules for naming identifiers in C, such as starting with a letter or underscore, and can contain letters, digits, and underscores.

Parameter List:

The parameter list specifies the inputs or arguments the function expects to receive when called. Each parameter is defined with its data type and a parameter name. Commas separate multiple parameters. If the function does not require any parameters, an empty parameter list or void can be used.

Function Body:

The function body is enclosed within curly braces {} and contains a collection of statements defining the function's behaviour. It includes the code that is executed when the function is called. 

Return Statement (if applicable):

If the function has a return type other than void, a return statement specifies the value the function will return. The return statement terminates the function's execution and returns the specified value to the caller. 

Syntax of a function definition

The syntax for function definition is as follows:

returnType functionName(type1 parameter1, type2 parameter2, ...) {
    // Function body
}

The function body consists of a collection of instructions that define what the function does. It may include variables, statements, and the return statement (if applicable) to return a value.

For example,

int getRectangleArea(int length, int breadth) {
    return length * breadth;
}

Calling User-defined Functions

We use a function call to invoke a user-defined function in C and transfer control to that function. The function call consists of the function name followed by parentheses. If there are any arguments, they are passed within the parentheses.

Here is the syntax for calling a user-defined function in C:

functionName(argument1, argument2, ...);

The function name is used to identify the specific function being called. The arguments (if any) are values or variables passed to the function. It's important to provide the arguments in the same order defined in the function declaration.

Let's consider an example to demonstrate a function call:

#include <stdio.h>

// Function declaration
int addNumbers(int x, int y);

int main() {
    int num1 = 10;
    int num2 = 5;
    int sum;

    // Function call
    sum = addNumbers(num1, num2);

    printf("Sum: %d\n", sum);

    return 0;
}

// Function definition
int addNumbers(int x, int y) {
    int result = x + y;
    return result;
}

Here, we have a user-defined function, ‘addNumbers’, comprising two integer arguments, x and y, which processes their sum as an integer. Within the main function, we declare two variables, num1, and num2, to hold the numbers we want to add. We then call the addNumbers function and pass the values of num1 and num2 as arguments. The returned sum is stored within sum variable and then printed to the console.

The output of the above program would be:

Sum: 15

Creating a Function Call

When calling a function in C to calculate its output, we create a function call. The program's control is transferred to the called function, and its function body is executed. To make a function call, we use the function name along with the values of the arguments enclosed in round brackets in the exact order defined in the function declaration.

There are two types of function calls:

Call by Value:

The argument values are copied to the function parameters in a call-by-value function, and we cannot modify the actual values. Copies of the variables passed to the function are created, which remain in the stack segment of memory and are overwritten when the program leaves the scope of the called function.

Call by Reference:

In call by reference, the address of the arguments is passed to the function parameters, allowing us to modify the actual values of the arguments outside the function scope.

Return Statement

The return statement returns a value from a function and terminates its execution, returning control to the calling function. It allows us to return a result or output from the function to the calling code. The returned value must match the data type defined in the function declaration and definition.

Syntax of the return statement:

return expression;

If present, the expression is evaluated, and its value is converted to the return type defined by the function. If a function has a return type of void, no return statement is required inside the function definition.

If no return statement exists in the function body, the program's control reaches the calling function after executing the last line. However, it is considered good practice to include a return statement, even for void functions, to clarify the intention.

The C compiler may warn if there is code after the return statement, indicating that it is unreachable and will never execute.

Example:

#include<stdio.h>

double getRatio(int numerator, int denominator) {
    // Typecast the denominator to double
    // to avoid integer division
    // The result is typecasted to the return type of the function
    return (numerator / (double) denominator);
}

int main() {
    int a = 3, b = 2;

    double ratio = getRatio(a, b);
    printf("%d / %d = %.1lf", a, b, ratio);

    return 0;
}

Output:

3 / 2 = 1.5

In this example, the getRatio function calculates the ratio of two integers. To avoid integer division, we typecast the denominator to double. The calculated ratio is directly returned from the function and stored in a variable of type double in the main function. Finally, the ratio is printed to the console.

The return; statement can be used in functions with a return type of void to indicate an empty return expression as well.

Passing Arguments to a Function

Passing arguments to a function allows us to provide data to the function for it to perform operations or calculations. Arguments are the values we pass to a function during a call. These arguments are received by the function parameters, defined in the function declaration and used within the function's body.

For example, consider the function:

int getRectangleArea(int length, int breadth) {
    // function body
}

In this function, length and breadth are the function parameters. When calling this function, we pass values for length and breadth as arguments. In the main function, we can pass arguments like this:

int l = 5, b = 10;
int area = getRectangleArea(l, b);

Here, l and b are the arguments being passed to the getRectangleArea function. These values are received by the function parameters' length and breadth within the function's scope.

It's important to ensure that the data types of the function arguments match the data types of the corresponding function parameters. If there is a mismatch, the compiler will throw an error.

When passing multiple arguments to a function, it's crucial to maintain the order of the arguments as defined in the function declaration. The arguments are passed in the same order as the parameters are declared.

A function can also be called without any arguments if the function does not require any input data. Additionally, there is no limit to the number of arguments that can be passed to a user-defined function in C.

Conclusion

User-defined functions in C play a crucial role in code organisation, modularity, and reusability. We can improve code readability and maintainability by breaking down complex tasks into smaller, manageable functions. With the ability to pass arguments and return values, functions allow us to create flexible and efficient code structures. By leveraging functions effectively, we can enhance code structure, promote code reuse, and make our programs more modular and manageable. 

Students can also get an immersive learning experience with upGrad’s Executive Post Graduate Program in Data Science & Machine Learning course. This program can strengthen your decision-making skill while strengthening your programming abilities to hone proficiency in the competitive field of data science.

So, what are you waiting for, enroll now!

FAQs

1. What do we mean by user-defined function types?

User-defined function types refer to the various categories or classifications of user-defined functions based on their characteristics and purposes, such as functions with return values, functions without return values, functions with parameters, etc.

2. What is the difference between a user-defined function and a library function?

The programmer creates a user-defined function to perform specific tasks based on program requirements. In contrast, a library function is predefined and provided by a library or framework, offering commonly used functionality that can be readily used in programs without explicit implementation.

3. Can a user-defined function call another user-defined function?

Yes, a user-defined function can call another user-defined function. Function calls can be nested within one another, allowing for modular and reusable code organisation. This enables the decomposition of complex tasks into smaller, manageable functions, enhancing code readability and maintainability.

Leave a Reply

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