'When and why should I use void as the return type of a function in C?

I'm currently practising C and learning pointers and arrays. I watched a tutorial where the instructor changed the function from int aFunction() to void aFunction(). Of course, he didn't say why — that's why I'm here. So I'm wondering: when and why should someone use void as the return type for a function.



Solution 1:[1]

The token(s) that precedes the function name in the function declaration is the type of the value that the function returns. In this case there is just one token, but type names may consist of multiple tokens. When you want to return an integer object, you can specify the return type to be int. When the function won't return anything, you use void return type.

Solution 2:[2]

In C, you have to tell the compiler what are each of the types of the variables you declare. That is why you have things like int and char*.

And functions’ return values are no different. Compiler has to know what each of your functions return types are to work properly. Now if you have a function like add(int a, int b) typically you would want its return type to be of integer, that is why you would define it as

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

Now consider you have a function that doesn’t return anything at all, now you need to tell your compiler that this function returns nothing. That is why void is used. You use void when the function does something but in the end doesn’t need to return any value to the program it was called from. Like this one:

void printAdd(int a, int b)
{
    printf(“a + b = %d”, a+b);
}

We are doing a bunch of stuff here but the result from the addition is not returned or stored but rather printed to the screen.

You can use the first function add() like this:

int abc = add(5, 7);
// abc is 12

while you can only use the second function like

printAdd(5, 7);
// you cannot store the value because nothing is returned.
// 5 + 7 = 12 is printed to the screen

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2