C Functions Tutorial with Examples

    0 Votes

C programs often need a piece of code to be executed more than once. We can use loops for such purposes, but what if we want to run them from different parts of the code? It can be simple validity check or a more complex operation, but as it is used from different parts of the program we can’t use loops. Of course, writing same code multiple times is a solution, but not very programmer like way (for example, if you want to change the algorithm, you've to change it at multiple places). It would be better if we can write the repeating code once and refer to it from where ever required. That’s exactly what functions in C language are for. In this chapter of C programming tutorial, let's look at the concept of "functions".

Use of Functions in C

In C, a function is nothing but a self-contained block of code that can be accessed by specifying its name and providing the appropriate arguments to it from any part of the program. The argument list must be separated by commas. If the function does not require any arguments, then the function name will be followed by the empty parenthesis. The arguments used in the function call are known as actual arguments. The arguments in the first line of function definition are called formal arguments or actual parameters. The actual arguments must be of the same data type as the formal arguments. During the function call, values of actual arguments are copied into the formal arguments.

Sometimes functions return values too. In that case, the value returned by the function can be assigned to a variable using assignment operator. Function calls may happen multiple times from different parts of the program and the actual argument may vary. But in all function calls the different arguments must be of the same data type as the formal argument and also the number and order of arguments must be same.

The general form of function prototypes looks like ...

data_type function_name(data_type1 argument1, …, data_typeN argumentN);

and the function call will look like -

function_name(argument1, argument2, … , argumentN) ;

Example of a Function in C

A simple program with function call will look like this...

#include<stdio.h>
void print_hello();

void main()
{
   print_hello();
}

void print_hello()
{
    printf("Hello world\n");
}

This program just prints "Hello world" on the screen. The line after '#include' directive is called a function prototype. It declares that function 'print_hello' does not return anything and does not take any arguments. The function call is inside the 'main()'. After 'main', there is function definition which defines what the function does.

Placement of the Function

The function prototype should be defined before 'main' function, so that when the functions are called, compiler can decide whether the function exists or not or is on a different file. The function call can be placed in the 'main' function or even in another function body. The function body or definition can be placed before 'main' or after 'main' . If the function definition is placed before the invocation, then there is no need for function prototype.

In case the whole program is divided in multiple files, the function prototypes most likely to be included in the header file (files with '.h' extension). The file from which the function is invoked must include the header file containing the prototype. The function body in that case can be in a source file ('.c') or can be placed inside the header file as well.

Functions with Multiple Parameters

As mentioned earlier, functions can have more than one argument. In that case the function definition, prototype and the function call must have arguments separated by commas. Consider the simple program where the function 'print_bigger' accepts two arguments.

#include<stdio.h>
void print_bigger(int first, int second);

void main()
{
    print_bigger(15, 27);
}

void print_bigger(int first, int second)
{
    if(first > second)
    {
      printf("%d is bigger", first);
    }
    else if(first == second)
    {
      printf("both number are same");
    }
    else
    {
     printf("%d is bigger", second);
    }
}

Here the function 'print_bigger' takes two arguments and prints the number which is bigger than the other or prints "both number are same" if both arguments have the same value.

User Defined Functions and Library Functions

We have already seen both user defined and library functions. User defined functions are the functions that are defined by the programmer and not provided by C. The library functions or system defined functions are provided by C libraries, like 'printf', 'scanf' etc.

There are a lot of library functions available in C. The standard C library provides functions like 'printf', 'scanf', 'putc', 'getc', 'puts', 'gets' etc. Functions like 'toupper', 'tolower', 'isalpha' etc., have their definitions in header file 'ctype.h'. 'sin', 'cos', 'sqrt' have definition in 'math.h' file.

Concepts Associated with Functions in C

A function is not executed until it is called (invoked) from the program. By function call we mean, the program provides the function with input data in the form of arguments. The value of the argument is passed to the function and copied in the formal arguments. If the formal arguments are modified inside the function it will not affect the value of the actual arguments in the program unless the arguments are passed as pointers.

#include<stdio.h>
void function1(int a);

void main()
{
    int i = 3;
    function1(i);
    printf("Value of i : %d", i);
}

void function1(int a)
{
    a++;
    printf("Value of a:%d\n", a);
}

In the above example, value of variable 'a' will be printed as 4 but the value of 'i' will be printed as 3. Because, even if value of the argument is incremented inside the function, it would not affect the value of variable 'i' in 'main'. When the function is called, the program execution goes to the function and after executing the statements in the function, it returns to the same position.

Function parameters

The function parameter can be of any data type, char, int, float, string or even an array/user defined data type. The arguments passed from the caller (from where the function is called), must be of the same data type as of function parameters. If there is a mismatch between those two, it will generate a compiler error. Even sometimes the compiler may fail to spot the difference, in which case your program may act erroneously.

Variable Argument Functions in C

C function can also have variable number of arguments. For example functions like 'printf' and 'scanf' can take any number of arguments. The variable argument function has a function prototype like the one given below

data_type function_name(int, data_type argument1, …);

The three dots (…) in function prototype defines that it is variable argument. Note that the first argument is an integer which represents the number of arguments. Some utility methods are required to make use of variable arguments in C and it is defined inside header file 'stdarg.h'.

How to Use Variable Argument Function in C

First step in making use of variable arguments in the function definition is to use the macro, 'va_start', which is defined in header file 'stdarg.h'. This macro initializes a variable of type 'va_list' with the argument list. Then we need to use 'va_arg' macro and 'va_list' variable to access each individual parameters. When the processing is finished, use the macro 'va_end' to release the memory used by 'va_list'.

Variable Argument Functions Example

#include <stdio.h>
#include <stdarg.h>

int calculateSum(int count,...)
{
    va_list valist;
    int sum = 0.0;
    int i;
    va_start(valist, count);
    for (i = 0; i < count; i++)
    {
       sum += va_arg(valist, int);
    }
    va_end(valist);
    return sum;
}

int main()
{
   printf("Sum of 1, 2, 3 = %d\n", calculateSum(3, 1, 2, 3));
   printf("Sum of 1, 2, 3, 4 = %d\n", calculateSum(4, 1, 2, 3, 4));
}

Function with Return Value

Function as mentioned earlier can return some value. The number of values that can be returned by a function is restricted to 1 in C. If a function calculates more number of output values, you can use a structure/union to hold each of them and return it. The type of value returned by the function must be defined in the function prototype and definition. To illustrate function with return value a simple program is presented below.

#include<stdio.h>
int add(int a, int b);

void main()
{
    int sum = 0;
    sum = add(23, 35);
    printf("Sum : %d", sum);
}

int add(int a, int b)
{
    int c = a + b;
    return c;
}

In the above example, the function 'add()' takes two arguments of integer type and returns an integer value. Notice the return statement in the 'add()' function which returns the value to the caller.

Recursive Functions

Recursive functions are those functions which call themselves directly or indirectly. If a function calls itself again, that will make a repetition and will work like a loop. In order to make a logical end to the repetitive call, we have to add an expression to break the flow of recursive call. Consider the program of factorial which finds the factorial of the input number. It can be written using recursive function as given below.

Recursive Function Example in C

#include<stdio.h>
int factorial(int n);

void main()
{
    int num;
    int fact;
    printf("Enter the number:");
    scanf("%d", &num);

    fact = factorial(num);
    printf("Factorial of %d is %d", num, fact);
}

int factorial(int n)
{
    if(n == 1)
    {
        return 1;
    }
    else
    {
        return (n * factorial(n -1));
    }
}

Let’s take the input number as 3. Then the factorial function is called with value 3. Inside the function it will check whether 3 is equal to 1 and then execute the 'else' statements. The return statement will look like 'return (3 * factorial (2))'. Now 'factorial(2)' will again enter the 'else' statement as the 'if' condition fails. This time it will return '(2 * factorial(1))'. Now 'factorial(1)' returns value 1 which will result the output (3 * (2 * 1)) i.e. 6.

One thing to remember while using recursive function is that if you omit the check expression or if the expression never be satisfied, it will cause an infinite loop. Recursion is another way to simulate loop and can be replaced by a simple loop statement (also called iteration)

Popular Videos

communication

How to speak so that people want to listen.

Got a tip or Question?
Let us know

Related Articles

C Overview and Basic Syntax
Data Types in C Language
C Qualifiers - Constant and Volatile type Qualifier
C Type Casting with examples - float to int / int to char / int to long
C Constants and Literals
C Operators - Arithmetic, Assignment, Relational and Logical
C Operators - Bitwise Operators and Conditional Operators
C Operator Precedence and Associativity Table with Examples
C Input and Output Statements
C Format Specifiers for printf and scanf
C Decision Making Control Structures - 'if', 'if - else', nested 'if', 'switch'
Loops in C - for, while and do...while Loops
C 'break', 'continue' and 'goto' Statements to Control Program Flow
C Preprocessor Directives and Macros
C Arrays - Dynamic, 2d and Multidimensional with Examples
C Strings - Internal Working and Functions with example
C Pointers basics explained with examples
Structures in C Programming with Example
Unions in c programming with example
C Storage Class Specifiers - auto, register, static and extern