Use of void function?

I am beginner and I was wondering why does one use void function? For example in the below code, the message can be printed directly after int main () and hence there is no need to fist run the main function and then go back to void function to print message.

Can someone explain me the use of void functions in a C++ code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // void function example
#include <iostream>
using namespace std;

int a,b,r;

void printmessage ()
{
  cout << "Sum of the numbers is: " << r << endl;
}

int main ()
{
  a = 5;
  b = 6;
  r = a + b;
  printmessage ();
}
First, avoid global variables, unless you really need them.

What if the function does something more complex and you need to do that set of operations multiple times, possibly in multiple functions?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

void printmessage( int sum )
{
  std::cout << "===========================\n";
  std::cout << "|                                                    |\n";
  std::cout << "Sum of the numbers is: " << sum << '\n';
  std::cout << "|                                                    |\n";
  std::cout << "===========================\n";
}

int main ()
{
  printmessage( 42 );
  int a = 5;
  int b = 6;
  int r = a + b;
  printmessage( r );
  printmessage( r + a );
  printmessage( 7 );
}

Would you prefer to copy-paste-and-edit the mere 5-liner output command into your main() N times?


For example in the below code

Yes, one can always find an example, where the use of particular feature gives no advantage. Are they useful examples?


Edit: Now, after posting, I see that the output formatting in my example is atrocious. I would have to fix the code that is in the function once, while same repeated statements in main() would need more repetitive work (and thus chances for novel mistakes).
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
to answer the question, not every function must return a value. 

your simple example is perfect in that regard: 
a function that just prints something does not need to return a value.  
 A void function is one that does not return a value, so you use void in these 
situations where you don't need it. 

non void functions (as you may know) have the form

type functionname( ... parameters) 
{
     code;
      return variable_of_type;
}

this is when you DO need the return value.   
eg 
int f(int x)
{
    return x*x;
}

...
main()
{
y = f(x); 


you will see the use of both types of functions as you get deeper in to the language. In the meantime, do avoid the global variables, they are a bad habit to break immediately.
Last edited on
Void functions are very useful and not limited to a specific type of data, as they return nothing. You can pass variables by reference into them and work with the variables. Look at this...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  // void function example
#include <iostream>
using namespace std;

void printmessage (int r)
{
  cout << "Sum of the numbers is: " << r << endl;
}

void square(int &myint) {
 myint *= myint;   
}

int main ()
{
int a,b,r;

  a = 5;
  b = 6;
  r = a + b;
  printmessage (r);
  square(a);
  cout << a << endl;
  square(b);
  cout << b << endl;
 square(r);
  cout << r << endl;

}
Last edited on
Um. I am sorry, but I still do not understand.
I just started learning C++.

Like in Manga's code. Why bother with void function for printing r value?
When i can just code it in the main function directly.
1) Because you might want to call it more than once - look at the use of the square function in Manga's example.

2) Because it makes code easier to read, and understand, and test, and maintain, if you break it down into small, well-named units.
you can use it in your main code directly, theres no problem with that.

manga is demonstrating that some functions dont return values.

some programming languages make a distinction between those that do and those that dont, calling them PROCEDUREs and FUNCTIONS, the common name for both is "subroutines", procedures are functions that do not return a value. In C/C++ we use the "void" keyword to indicate a procedure, and you will see that void functions never return a value. if they contain a return statement it will just be return;

jonnins answer has all the info you need, ive just kinda repeated what he said.

when you decide to put some code in a function, you also need to decide if that function needs to return you some value. If not, make it void.
Last edited on
C++ is notorious for using functions. Usually you will include different files into the main .cpp file in order to make everything look cleaner. By using a function, such as a type void, it allows your code to:

1) Look cleaner, and the individual who may go back and look at this code knows how to find the usage of it easily,
2) Multiple use: Let's say you constantly have to output different numbers that are being added together, or something of that idea; this function can be constantly called and will dynamically change.
3) Main is small. This goes along with my first point, where it'll make everything more clean.

Now, the function type void is used because you will not be returning anything from this function. You are purely using the function that you included to print out a message; by this, I mean that you aren't returning a number back to the int main() portion of the program, therefore, type void is used. Now let's say you wanted to add two numbers together and return them to your int main(), depending upon what kind of numbers are being added, depends on what type your function takes. Let's say you're adding numbers that are of type double, and these are being added in a function called, hmmm, let's say double addingDoubles(double num1, double num2). Here, we can look at the function prototype and assume two things, we are going to add two doubles, and we have the function as a type double, because we have doubles going in, and we will have a double coming out.

Now, in the main program, you could call the function and return the number from the added doubles, like so:

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    double answer;
    double num1 = 2.1;
    double num2 = 3.4;
    
    answer = addingDoubles(num1, num2);

    cout << "The answer of our two numbers added together is: " << answer << endl;

    return 0;
}



Now, this is entirely unnecessary, because we could simply add in main, and output there. However, we can use this addingDoubles in different places now.

The point I'm trying to make, is that whether you have a function of type double or in your case, of type void, it's purely what you're trying to return, and since your function doesn't require anything to be returned, you can use void.

Quick tip in my experiences:

Normally, any time I've coded large programs in C++, void functions are normally going to be used for input/outputs and reading and writing files.

If you have any other questions, just let me know.

Your friendly Computer Engineer,
fnx
fnx wrote:
C++ is notorious for using functions.

Huh? What on earth are you trying to say here?

Firstly, there's nothing wrong with functions, so why would it be a thing that would make a language "notorious".

Secondly, I don't believe that function use is more prevalent in C++ than it is in most other languages.
Last edited on
atreyi114 wrote:
Why bother with void function when i can just code it in the main function directly?

MLOC

Some projects have multiple Million Lines of Code. Why arrange all that into functions, if you could just write all the lines into the main?

Why have many short reusable blocks of code, each of which performs one task and is easy to read and maintain, if a single massive wall of text gives the right result (in initial test)?



Have you seen classes yet? Classes have member functions.

Some classes have setter functions that simply update some internal value of a class object. Those functions do not need to return any value. Therefore, they have the return type void.

Code in main() cannot even access the private internals of objects. Thus, you have to use the "void functions".

Why bother? You can open classes wide open; no need for setters then. Because those "bothersome, self-made restrictions" prevent you, the coder, from making trivial mistakes.
Maybe some functions are short. So you may think why bother. But as you study code more, you will begin to get more complex and longer functions. This is where it is better to reuse blocks of code as opposed to retyping lengthy sections over and over.
At work many of our functions are one line long :) and yes i mean MANY.

functions and classes and modules and packages and all the other mechanisms for chunking code together are used to organise our code. Even if its just one line, if (ReadyToGo()) {} is far easier to read than if (a > 10 && c(a) < (b/2)) {} and if our criteria change we know exactly where to go in the code to change it.

rely on them HEAVILY! without them your code will grow to look like spaghetti, and after 40 or 50 hours of coding you will become stuck, your code will become harder and harder to modify.

bricklayers are always careful how they lay their bricks, even if the wall is only 3 bricks high. they are developing and maintaining their skills that let them build houses.

That's where you are right now, building a 3 brick high wall so you can learn how to put bricks together. It may feel pointless, but these are just learning exercises that you're doing, and your "wall" is disposable. But if you don't train yourself to build a "straight" wall, you will never be capable of building a house, and then you would have to ask yourself "was it all worth it?"

fnx wrote:
void functions are normally going to be used for input/outputs and reading and writing files.

I would disagree with that, predicting what different functions types will "probably" be used for is misleading. In truth, when you decide you are going to break some code out in to a function the return type (if any) will be obvious to you by the time you've coded it up.

@everyone
fnx wrote:
since your function doesn't require anything to be returned, you can use void

hmm, how we describe things leads peoples thoughts, perhaps we should all be saying "since your calling code doesn't require anything back from the function it can return void", because that's what we're all thinking right? when i'm actually coding i'll think "hmm, i'l stick that in a function and it can return me so and so". i hope i'm pretty normal in thinking like that.
Last edited on
To OP. In your original example we see a void function that prints a message. And it was called only one time. In that example, you are correct. Why put that function there if it was to be used only once. But in big programs, functions get called many times. If your function was typed out each time you meant to use it, but you made an error in one of the uses, you might have to go through all you program to find the mistake. But by making it a function that you reuse, it is less likely to suddenly contain an error, and if it did, you would know right where to go in your code to fix it. As Jaybob66 points out even one line functions are better than no functions. But they become real time savers if the function is long.

Imagine a function that prints out Jaybob's last post. To reprint that message I could just call Jaybob66() each time. And it would be a void function if I did not need a Jaybob returned to me each time! :)
Last edited on
Thanks a ton! Understood now.
Topic archived. No new replies allowed.