Functions in C

·

4 min read

Play this article

What is a function

A function can be defined as a unit of related lines of code. These lines are supposed to do a particular task. Functions are a major part of programming.

In our case, we'll be talking about functions in the C programming labguage. We'll go over each part of a function, what they mean, its importance and what is expected.

The basic structure of a function

A function is composed of four main parts i.e. the return type, the name of the function, the values it accepts and the logic of the function.

Let's analyze a simple function as an example.

int main()
{
    printf("Hello, Functions");

    return (0);
}

Let's look at the parts that make up the main function.

  • int -> It specifies what the function will return. This can be any supported data type in C.

  • main -> This is the name of the function. It can be any name as long as it is not a keyword in C or violates the C naming rules. In our case the name is main. main is a special function because it doesn't have to be called explicitly by us it is called by the linker during compilation.

  •     printf("Hello, Functions");
    
        return (0);
    

    This is the logic of the function. It is here that we specify what we want the program to do.

Now that we have seen the parts of a function, we can look at how to make our functions.

To get started we can write a simple function that takes in a word and then returns if it has a vowel and which vowels.

#include <string.h>
#include <stdlib.h>

char *get_vowels(char *word)
{
    /* First duplicate the word given so that we can be
    * sure that this is a valid array of characters
    * and not a string literal.
    * If you are sure of what you'll get, then skip this part
    * as it may involve memory freeing.
    */

    char *dup_str = strdup(word);
    short i = 0, j = 0,l = 0; // Define to avoid NULL
    char vowels[] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; // Define the vowels
    /* I have allocated more memory than will ussually be
    * required in this situation, this is not ideal.
    * This is for demonstration only
    */
    char *found_vowels_arr = malloc(sizeof(char) * (strlen(dup_str) + 1));
    // We will use a simple for loop to check for the chacters

    for (i = 0; i < strlen(dup_str); i++)
    {
       for (j = 0; j < 10; j++)
        {
            if (dup_str[i] == vowels[j])
                found_vowels_arr[l++] = dup_str[i];
        }
    }

    return found_vowels_arr;
}
/*
This code will return all the vowels (no matter if they are unique or 
not). If you want you can extend to only return unique. Please don't 
this code anywhere as it has memory problems. This is just for 
demonstration.
*/

As we can see from our example, we have the function name "get_vowels" that returns an array of characters. The function is used to manipulate the values passed to it and return a value (if void nothing is to be returned). The value produced by a function is meant to be deterministic in nature and any weird behaviour can be classified as a bug.

The "get_vowels" function can be used like this:

#include <stdio.h>

int main(void)
{
    char *word = "ThisisAwordwithVowels";

    printf(get_vowels(word));

    return 0;
}

If you want to implement a void function (a function that doesn't return anything), then you can use as follows:

#include <stdio.h>

void greet_user(char *user)
{
    printf("Hello, %s", user);
}

int main(void)
{
    greet_user("Gekko Wrld");

    return 0;
}

void functions are not allowed to return anything or be its "value" assigned to anything.

Benefits of functions

Functions offer modularity in the codebase. Functions can be manipulated independently without necessarily affecting the whole other functions. If the codebase is modular then if a problem arises, it is easier to diagnose and fix.

Reusability is also a big reason why to use functions. If you have a function let's say that performs addition and adds a magic number to it, if this process is required in many places, then it can be easier to use a function to avoid duplication of code.