Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If void() does not return a value, why do we use it?

Tags:

c++

types

void

void f() means that f returns nothing. If void returns nothing, then why we use it? What is the main purpose of void?

like image 222
Mustafa Muhammad Yousif Avatar asked Jul 19 '12 11:07

Mustafa Muhammad Yousif


People also ask

Why do we use void as it is returning nothing?

The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values.

What is the purpose of using void?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters.

What does it mean when a function does not return a value?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.


1 Answers

When C was invented the convention was that, if you didn't specify the return type, the compiler automatically inferred that you wanted to return an int (and the same holds for parameters).

But often you write functions that do stuff and don't need to return anything (think e.g. about a function that just prints something on the screen); for this reason, it was decided that, to specify that you don't want to return anything at all, you have to use the void keyword as "return type".


Keep in mind that void serves also other purposes; in particular:

  • if you specify it as the list of parameters to a functions, it means that the function takes no parameters; this was needed in C, because a function declaration without parameters meant to the compiler that the parameter list was simply left unspecified. In C++ this is no longer needed, since an empty parameters list means that no parameter is allowed for the function;

  • void also has an important role in pointers; void * (and its variations) means "pointer to something left unspecified". This is useful if you have to write functions that must store/pass pointers around without actually using them (only at the end, to actually use the pointer, a cast to the appropriate type is needed).

  • also, a cast to (void) is often used to mark a value as deliberately unused, suppressing compiler warnings.

    int somefunction(int a, int b, int c)
    {
        (void)c; // c is reserved for future usage, kill the "unused parameter" warning
        return a+b;
    }
    
like image 135
Matteo Italia Avatar answered Nov 09 '22 06:11

Matteo Italia