top

Search

C Tutorial

.

UpGrad

C Tutorial

Functions in C

Introduction

A function in C is a block of code that runs only when it is called. You can pass data (known as parameters) into a function. The functions in C are used to perform specific actions. They help you to optimise and reuse the code. You only have to define the function’s code once and use it multiple times.

Generally, a C function is defined and declared in a single step. The reason is the function definition always begins with the function declaration, so you don’t have to declare it explicitly.

Advantage of functions in C

Functions in C serve an extremely useful feature and provides the following advantages:

  • The functions decrease the iteration of the same statements in a program. So, they decrease the program’s size.

  • The function improves code readability by offering modularity to the program.

  • Functions can be called multiple times from different parts of a program, promoting code reusability. 

  • They make programs easy to understand and manage by breaking a large program into smaller pieces.

Basic Syntax of Functions

Here’s the basic syntax of function in C:

return_type function_name(parameter1, parameter2, ... parameterN) {
body of the function
}

General Aspects of Functions in C Programming

Three general aspects of functions in C programming are:

i. Function Declaration

ii. Function Call

iii. Function Definition 


i. Function Declaration

The function declaration informs the compiler about the name, data type of parameters, number of parameters, and return type of a function. It is optional to write parameter names during declaration because you can do that when defining the function.

ii. Function Call

The compiler executes the function call in C. You can call the function anywhere in the whole program. But make sure to pass the number of arguments (of the same data type) as specified when declaring the function. 

iii. Function Definition

It means defining the statements that the compiler will execute during the function call. It represents the body of the function. Function definition should return only one value upon the completion of the execution.

Here’s one of the easy-to-understand function in C programming examples that illustrates all three general aspects of a function. 

#include <stdio.h>

// Function declaration  

int max_num(int x, int y)

{

    // Function definition

    if (x > y)

      return x;

    else

      return y;

}


int main(void){

    int a = 11, b = 19;  

    // Calling the function to determine the larger of the two numbers

    int p = max_num(a, b);  

    printf("The biggest number is %d", p);

    return 0;

}

Output:

The biggest number is 19

The first part of the above program declares the function max_num, whose data type is int; the variables passed are x and y. The function definition part compares the value of two variables, and based on the comparison, it returns the value. The function calls the max_num and prints the output based on the comparison.

Types of Functions

Types of Functions in C

There are 2 types of functions in C programming:

Library Functions: 

They are also known as built-in functions. They are directly usable; no need to define them. The examples of these types of functions in C are printf(), scanf(), puts(), gets(), floor(), ceil(), etc.

User-defined functions: 

The functions which the programmer creates are called user-defined functions. The user-defined functions in C should be declared and defined before being used. These functions can be improved and altered as per the programmer’s need.  They can be used multiple times. So, they decrease the code’s complexity.

Header Files for Library Functions in C Programming

The header files in C contain a set of predefined standard library functions and other entities. They are included in a program using #include <header_filename.h>. These files provide the necessary declarations and definitions for the C standard library. 

The example of a header file for library functions in C is “#include <stdio.h>”. It includes the standard input/output functions.  

Return Value 

A C function doesn't need to return a value from the function. If you don't want to return value from the function, you must use void for the return type.

Here is one of the function in C programming examples that demonstrates the use of a function without a return value.

#include <stdio.h>

// The below function prints a greeting message
void greet()

{
    printf("Welcome to C programming");
}

int main()

{
    greet();  // Calls the greet function
    return 0;
}

Output:

Welcome to C programming

In the above example, the greet function has a return type void, so it doesn’t return any value. It only prints the message using printf.

If a function needs to return a value, you can specify a return type other than void, such as int, char, or any other appropriate data type.

Here’s an example demonstrating using the C function that returns a value.

#include <stdio.h>

// The below function calculates the sum of two integers
int sum(int a, int b)
{
    int c = a + b;
    return c;
}

int main()
{
    int m1, m2;

    printf("Please enter two numbers: ");
    scanf("%d %d", &m1, &m2);

    int addition = sum(m1, m2);
    printf("The sum of two numbers is: %d\n", addition);

    return 0;
}

Output:

Please enter two numbers: 5 6
The sum of two numbers is: 11

In the above example, the sum takes two integer values a and b. It calculates the sum and stores the result in variable c. Subsequently, the function returns the result. 

The main function prompts the user to enter two numbers. The sum function is called in which the entered numbers are passed as arguments. The value returned from the sum function is assigned to the addition variable, which is finally printed to the console.

Different aspects of function calling

Function calling in C incorporates various aspects. They are discussed below.

i. Function Declaration:

It mentions the name of the function, the types of its parameters (if exist), and its return type.

For example,

int add(int p, int q);


ii. Function Definition:

This aspect represents the actual implementation of the function. It contains the function body that includes the statements to be executed.

For example,

int add(int m, int n)
{
return m + n;
}



iii. Function Parameters:

Functions in C can accept zero or more parameters (also known as arguments). These parameters are used to pass values to that function.

iv. Return Values:

Functions can return a value to the caller through the return statement.

v. Calling Conventions:

Calling conventions specify the conventions and rules for the way function calls are invoked and the way parameters are passed.

vi. Function Call:

If you want to call a function, you just need to use its name followed by parentheses. There may be arguments inside parentheses.

For example,

int outcome = add(5, 6);

Example for Function without argument and return value

#include <stdio.h>

// Function declaration
void printhelloMessage();

// Function definition
void printhelloMessage()
{
printf("Here is your C program!\n");
}

int main()
{
// Calls the declared function
printhelloMessage();

return 0;
}

Output:

Here is your C program.

In the above program, the defined function, i.e., printhelloMessage(), neither has arguments nor a return value. It simply prints the message written in the printf function.

Example for Function with argument and without return value


Output:

#include <stdio.h>

// Function declaration
void printSum(int m, int n);

// Function definition
void printSum(int m, int n)
{
int sum = m + n;
printf("The addition of %d and %d is %d\n", m, n, sum);
}

int main()
{
int number1, number2;
printf("Please enter two numbers: ");
scanf("%d %d", &number1, &number2);

// Calls the function
printSum(number1, number2);

return 0;
}

Please enter two numbers: 5 7
The addition of 5 and 7 is 12


In the above program, the defined function printSum accepts two arguments, i.e., m and n. It calculates the sum of the values of these arguments. The printf function in the main body calls this function, and finally, the program prints the sum of the numbers.

Recursive Functions in C Programming

The functions in C are recursive if they can call themselves until the exit condition is fulfilled. 

#include <stdio.h>

// The following recursive function calculates the Fibonacci sequence
int fibonacci(int m)
{
    if (m == 0)
{
        return 0;
    }
else if (m == 1)
{
        return 1;
    }
else
{
        return fibonacci(m - 1) + fibonacci(m- 2);
    }
}

int main() {
    int num;


printf("Please enter a number to calculate the Fibonacci sequence: ");
    scanf("%d", &num);
    printf("Fibonacci sequence of %d is %d\n", num, fibonacci(num));
   
    return 0;
}

Output:

Please enter a number to calculate the Fibonacci sequence: 16
Fibonacci sequence of 16 is 987

In the above program, the ‘fibonacci’ function generates the Fibonacci series up to the given number using recursion.

Inline Functions in C Programming

When you use functions in C, the pointer for execution flow transfers to the function definition after the function call. So, you need an additional pointer that jumps to the definition and returns. The use of inline functions helps prevent the use of an extra pointer.

Inline functions are functions wherein rather than calling the function, we substitute it with the program code. Hence, the pointer doesn’t have to transfer back to the definition. To make an inline function, you must use the keyword inline before a function.

The syntax of an inline function is:

inline function_name (){

   //function definition

}

Here’s an example program that uses an inline function in C:

#include <stdio.h>

// Inline function is defined to calculate the minimum of two numbers
static inline int min(int a, int b)
{
    return (a < b) ? a: b;
}

int main()
{
    int m1, m2;

    printf("Please enter two numbers: ");
    scanf("%d %d", &m1, &m2);

    int minimum = min(m1, m2);
    printf("The minimum of %d and %d is %d\n", m1, m2, minimum);

    return 0;
}

Output:

Please enter two numbers: 12 18
The minimum of 12 and 18 is 12

The given program uses an inline function in C to calculate the minimum of two numbers. The program prompts the user to enter two numbers, calculates the minimum using the inline function, and then displays the result.

C Library Functions

C library functions are built-in functions sorted together and stored in a common location known as the library. Each function accomplishes a specific operation. You can access various header files to define all standard C library functions. Using library functions helps you obtain the pre-defined output.

You must include the header file to use C library functions in your program. For example, if you need to use the printf() function, include the header file <stdio.h>.

Conclusion

Knowing how to create and use functions effectively helps you optimise your C program. With the understanding of general aspects of functions in C, as discussed above, you can easily practise and master C programming.

In addition to getting acquainted with the functions in C, check out upGrad’s Master of Science in Computer Science by Liverpool John Moores University can significantly assist you in your career advancement in the tech industry. 

Enroll now to begin your journey!

FAQs

Q. What are the advantages of user-defined functions?

The user-defined functions in C can be modified as per the requirement. These functions’ codes are reusable in other programs. These functions are easy to interpret, debug and maintain.

Q. What is a forward declaration in C?

Occasionally, we define the function after its call to offer better readability. In these cases, we declare functions before they are defined and called. This type of declaration is known as a forward declaration.

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

The function parameters are the variables defined in a function declaration. The function arguments are the values declared inside a function when the function is called. The function parameters are the names recorded in the function’s definition, whereas function arguments are the real values passed to the function during the function call.

Q. How can you return multiple values from a C function?

Commonly, it is not allowed to return multiple values from a C function. However, you can either use pointers to heap or static memory locations to return multiple values.

Leave a Reply

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