Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use void with a function?

I understand that void returns no values. So how does it work in conjuncture to a function?

My understanding is that the purpose of a function is to return a piece of information after doing something with it.

so why would I want to return no value, and how would this be beneficiary?

like image 290
Ozymandias Avatar asked Nov 14 '16 06:11

Ozymandias


People also ask

Should I use void functions?

You should use void. For then it highlights the fact the the method in question has side-effects, and it was designed to have side-effects. This does two things, First, it tells the reader that all non-void methods don't change state, so one can be sure that calling this method wont have any un-intended side-effects.

Why the data type void is used in C in dealing with functions?

The void type, in several programming languages derived from C and Algol68, is the return type of a function that returns normally, but does not provide a result value to its caller. Usually such functions are called for their side effects, such as performing some task or writing to their output parameters.


1 Answers

My understanding is that the purpose of a function is to return a piece of information after doing something with it.

In some (most of the) programming languages, functions have side effects also. Purpose of some functions is limited only to side effects and return value is not necessary. Such functions have void return type.

Some examples of side effects may be:

  1. Update a global
  2. File operation, logging etc where user doesn't want to know the status of operation
  3. Freeing resources
like image 196
Gyapti Jain Avatar answered Oct 12 '22 00:10

Gyapti Jain