Function in C: Types, Advantages and Use

Function in C_Types,_Advantages and Use

A function is a set of statements that together perform a specific task.  Every C program consists of one or more functions. The main() function is mandatory for the C program because it is the entry point of your C code from where your program is executed.

Before starting the function let’s see the advantage of the function. It helps us to understand why the function is important for any programming language.

Advantages of function:

  • The function increases the modularity of the program. A large problem can be divided into subproblems and then solved by using functions.
  • The function increases the reusability because functions are reusable. Once you have created a function you can call it anywhere in the program without copying and pasting entire logic. So you don’t need to write the same code again and again.
  • Because function increases the modularity of your program, so the program becomes more maintainable. If you want to modify the program sometimes later, you only need to update your function without changing the base code.

 

Now l think you able to understand the advantages of the function if you are not able to understand then don’t worry. I am going to explain the function step by step. So let’s started with the type of function.

Types of function:

At a broad level, we can categorize function in two types.

  1. Library function.
  2. User-defined function.

Note: We can also categorize function on their inputs and return types.

 

Library function:

Like other languages, C has many built-in library functions to perform various operations. for example for input-out operation, scanf and the printf function are used. Similarly for string manipulation strings functions are available like strcpy, strcmp, etc.

You need to remember before using any library function you must include the corresponding header file. For example, if you are going to use string functions, then you must include string.h header file using a pre-processor directive.

Let’s see an example code,

In this example code, I am using strcpy() to copy the string in an array and printf() function to print the array on the console.

#include<stdio.h> //for print and scanf
#include<string.h> //for string function

int main()
{
    char blogName[30] = {0};

    //copy string in array
    strcpy(blogName, "Aticleworld.com");

    //print the array
    printf("Blog Name = %s\n",blogName);

    return 0;
}

Output:

Blog Name = Aticleworld.com

 

User-defined function

We can also create a function according to our requirements. But before creating your own functions you need to know about three aspects of function.

  1. Function definition.
  2. Function call.
  3. Function declaration.

 

Function definition:

The function definition contains single or groups of statements that perform specific tasks. The function definition can be categorized into two parts function header and the function body. Let’s see the general syntax of the function definition.

return_type function_name(type1 argument1, type2 argument2, ...)
{
    local variables;
    
    statement1;
    statement2;
    
    //return require only function return something
    return (expression);
}

The first line of the function is known as the function header. It represents the signature of the function and consists of return_type, function_ name, and function arguments list. Here I am going to explain parts of the function step by step.

1. Return Type:

If your function returns any value then you have to mention the type (data type) of the return value. For example, if the function is returning integer then return_type will be int.

So you can say that return_type denotes the type of the value function returns. The return_type is optional, if omitted then it is assumed to be int by default.  In C programming, the function can either return a single value or no value. If the function returns no value, then we must use the void in place of return_type.

We use void when function performs any specific task without returning any value. Also as we know we can only return single type value from a function. So if we want to return multiple values from function then we need to use structure. See the below article,

Let’s see the example,

//function returning int
int test()
{
    int result;

    //function body to perform task
    
    return result;
}

 

 

//function is returning any value
void test()
{

    //function body to perform task
    
}

 

 

2. Function Name:

The function name must follow the C naming rule. The function name can be composed of letters, digits, or underscore. You can see the article for more detail “C variable and naming rule“.

 

3. Parameter List:

The parameter (argument) list is used to receive the value from the outer world. It is also known as a formal parameter. A function can have any number of parameters. If the function does not have any parameter then the parentheses are left empty.

We can pass the value in function two ways call by value or call by reference. These two ways are generally differentiated by the type of values passed to them as parameters.  You can see the article for detailed information “call by value and call by reference“.

Note: In C, if you left parenthesis empty but still you can pass the value and you will not get any compiler error. So sometimes we used void in parentheses to avoid passing any argument.

Let’s see example code,

When you will compile the code using C compiler you will not get an error.

#include<stdio.h>

void test()
{

}

int main()
{
    test(5);

    return 0;
}

 

But when you will compile this code you will get a compiler error.

function in c

 

4. Function Body:

The body of the function is a group of statements. It is the place where you write your logic and declare the variable as a requirement. The return statement is also part of the function body. As I explained above if your function is not returning anything that return_type should be void. Let’s a few examples to understand this logic.

The function addTwoNumber() accepts two integer arguments and returns an integer value. It performs the addition of two numbers and assigns the result to a third variable sum (temporary local variable). Here a and b are formal parameter which received the input from the callee function.

The statement which has written in curly braces is the body of the addTwoNumber() function.

int addTwoNumber(int a, int b)
{
    int sum = (a+b);
    
    return sum;
}

 

Similarly, we can create a function that returns no value and does not take any parameter. The displaying() is a function which only printing a message. It is the reason its return type void and parameter list is empty.

void displayMsg()
{
    printf("Hello Aticleworld");
}

 

 

Function Call:

If you want to use the created function, then you have to call the function. To call a function you must write the function name followed by arguments if required. If the function takes more then one argument, then you have to pass all arguments and each one will be separated by a comma (,) inside the parentheses ().

for example, here you can see, how we are calling addTwoNumber() function and passing the parameters followed by the name.

#include<stdio.h>

int addTwoNumber(int a, int b)
{
    int sum = (a+b);

    return sum;
}

int main()
{
    //Calling function to add two number
   int sum = addTwoNumber(10,5);

    // Print the sum
    printf("Addition of num1 and num2 is: %d\n\n", sum);

    return 0;
}

 

But if the function does not take any argument then you only need to use empty parenthesis with the function name.

#include<stdio.h>

void displayMsg()
{
    printf("Hello Aticleworld");
}


int main()
{
    //Calling function to display message
    displayMsg();

    return 0;
}

 

 

Function declaration:

The calling function needs some information about the called function. Like the number of parameters the function takes, data-types of parameters, and return type of function. Giving parameters name in function declaration is optional, but it is necessary to put them in the definition.

You should remember that if the function definition comes before the calling function then function declaration is not needed. For example:

#include<stdio.h>

int multOfTwoNum(int a, int b)
{
    return (a * b);
}


int main()
{
    int num1, num2, mult;
    // Ask user to enter the two numbers
    printf("Please Enter Two different values\n");
    // Read two numbers from the user
    scanf("%d %d", &num1, &num2);

    //Calling function to multiplication of two number
    mult = multOfTwoNum(num1, num2);

    printf("%d x %d = %d \n", num1,num2, mult);

    return 0;
}

Output:

Calling function in C

 

You can see that the definition of function multOfTwoNum() comes before the calling function i.e main(), that’s why function declaration is not needed.

But if your function defines in another file then you have to declare it before its use. Either you will get compiler error let’s see how we can declare multOfTwoNum() function.

int multOfTwoNum(int a, int b);


        or
        
int multOfTwoNum(int , int );

        or
        
int multOfTwoNum(int x, int y);

 

Note: Generally function declared in the header file and parameters and return type of function declaration must match with the function definition.

Let’s see complete code for a function declaration,

#include<stdio.h>


//function declaration
int multOfTwoNum(int a, int b);


int main()
{
    int num1, num2, mult;
    // Ask user to enter the two numbers
    printf("Please Enter Two different values\n");
    // Read two numbers from the user
    scanf("%d %d", &num1, &num2);

    //Calling function to multiplication of two number
    mult = multOfTwoNum(num1, num2);

    printf("%d x %d = %d \n", num1,num2, mult);

    return 0;
}

//function definition
int multOfTwoNum(int a, int b)
{
    return (a * b);
}

 

I hope you able to understand how to create the function in C and how to use the function. Now let see some query related to function.

 

Why do we need functions?

Here are following points that describe why do we need to use the function in C programming.

  • Functions help us in reducing code redundancy. Using the function we can avoid code repetition. for example, if lines of code using at many places in the project then we can create a function and avoid the code repetition. Also where you need these lines of code you can call the created function.
  • The code maintenance is easy with function because changes only in one place (within a function) will reflect everywhere where the function has been called.
  • The function increases the modularity of your program. It becomes really simple to read and use the code if the code is divided into functions.
  • The Functions provide abstraction. For example, we are using the strcpy() a library functions without worrying about their internal working.
  • The function also saves your memory because it avoids code repetition.

 

Can you create a function in the structure?

You can not create the function in structure in C programming. But using the function pointer you can do the same.

Read below mention the article,

 

How to pass parameters to the function?

You can read this article to understand this question “How to pass parameter in function“.

 

Recommended Articles for you:

One comment

Leave a Reply

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