Purpose of void? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Purpose of void?

If void returns nothing, than why do we need it? In which cases we use “void” instead of “int”?

5th Aug 2019, 8:23 PM
TheDoctor
TheDoctor - avatar
3 Answers
+ 4
D_Stark and sneeze nailed it and the short answer is similar to your question: We use void when the function don't need to return anything. That is, the method/function simply does the job on its own instead of being asked to do something and return a response. Clear as mud? 😉
6th Aug 2019, 12:37 AM
Zephyr Koo
Zephyr Koo - avatar
+ 3
Void means if this method gets used nothing is returned to were that method was called most of the time these methods will print somthing that's just because that peice of code is inside the method and gets executed. A return type of int means if this method gets called do some work with the arguments you passed in and return the result back to were that method was called but you promise that the result returned will be an int value.
5th Aug 2019, 11:36 PM
D_Stark
D_Stark - avatar
+ 1
Sometimes you just want a method to do something for you. Like this method (sorry I wrote it in c#) Why should it return a value ? public void PrintName(string Name) { Console.WriteLine(Name); }
5th Aug 2019, 8:41 PM
sneeze
sneeze - avatar