Someone please help me understand VOID in C++?

Pages: 12
hello i recently learned about the VOID function in C++ but even though i asked questions i was still left confused about it. people have given me examples but in reality i dont see exactly what the VOID does, when you execute your code.
for example if my program asks me for 3 inputs

this is an output example that i have seen when the code was executed:

enter number: 2 (user input)
enter second number: 4 (user input)
enter third number: 5 (user input)

here is your total: 11

**now this is not my code but if there were a VOID function in this code what would it do and how would you know that the program executed has a VOID function in the code?

I do realize that i do not have an example code written but what i am trying to gain from this is that i want to know what exactly does a VOID do and where or how would you see it in an executed program? I hope that makes sense if it doesnt let me know and i will try to be a little more clear.

any void example would be great but i would like for the void function to be explained as to what it will do with certain variables and so i will know when and how i can use it . Thank you so much in advance
Last edited on
void is nit a function, it is a type. It is most commonly used as a return type:
1
2
3
4
5
6
7
8
9
10
11
12
void f()
{
}
int g()
{
    return 1;
}

//...

int x = f(); //error, f does not return anything
int y = g(); //fine 
If the function return type is void, it does not return a value. The "return;" statement can be sued to exit the function before reaching the end.

if a function does not return void, like g, then it MUST have a return statement in all control paths. For some functions, it makes no sense to return a value, because it would have no purpose.

void means 'no type'
Last edited on
sorry im new to this please have patience :D.
but i dont understand. I do understand what the void does (does not return anything) but for that why would you include the function that you want to void, like for example what is the point in having that function if you are just going to void it? if you void it then you might as well not even create the function in the first place. Thats what im not getting.










Why does anyone ever create any functions at all then? If you can expain why you would create a function that doesn't return void, you can explain why you would create one that does.

The point of any function is that the code it uses would be in multiple places if the function did not exist. Could you imagine having to update code in several places every time you made a change? Functions solve this. Not all functions need to return a value. 'void' is just for the return type, the functions can still do everything that other functions do.
Some programming languages distinguish between a subroutine and a function.

A subroutine is a group of instructions that perform a specific task, and help to break down a large mass of code into manageable chunks. When the subroutine is called, control of execution is passed to that part of the code, when it completes, control is relinquished and execution continues from where it left off in the original code. (Again, another word, "procedure" is sometimes used instead of subroutine). Examples of a subroutine might be to clear the screen, or print out a heading.

A function can be regarded as a bit like a subroutine, but it has the specific aim of generating some sort of result, and passing that result back to the the code from where it was called. An example of a function might be to calculate the square root, or turn a string from lower-case to upper-case.

In C++, the term subroutine is not used, instead, the word function is used for both purposes. A function with a return type of void can be considered as roughly the same thing as a subroutine in other languages.
Last edited on
what is the point in having that function if you are just going to void it?
you don't void the function. Like LB already state the type in front the function is what the caller of the function gets. if void is placed in front of the the function it means the function does not return a value to the caller
The void keyword in front of a function simply instructs the compiler that this function does not (and should not) return a value. If you attempt to return a value from a function declared as void, the compiler will issue an error (or a warning, I can't remember).

Likewise if you don't return a value from a function declared as returning an int, the compiler will issue a warning.

void is a data type, just as an int or a double is, except void means no type.
Correct me if I'm wrong. But I think ideally void and return is useful if a function has multiple possible outcomes. for example if a program is designed to have the user to guess a number between 1 and 10 and the user guesses the number you would use something like this to end the function?

L B wrote
If the function return type is void, it does not return a value. The "return;" statement can be sued to exit the function before reaching the end.


unless I just took it out of context
Yes, putting return; will exit the function early.
1
2
3
4
5
6
7
8
9
10
11
12
13
int f1()
{
    std::cout << "A" << std::endl;
    return 7;
    std::cout << "B" << std::endl;
}

int f2()
{
    std::cout << "A" << std::endl;
    return;
    std::cout << "B" << std::endl;
}
These two functions are the same, except that f1 returns 7 and f2 doesn't return anything. In both cases, "B" will never be printed.
Last edited on
so B will never be printed , but the function will be executed anyways? you say
LB:
These two functions are the same, except that f1 returns 7 and f2 doesn't return anything. In both cases, "B" will never be printed.
so why would you create and void the f2 function if the f1 function does the same thing. what would be the purpose of creating the f2 function? The thing is, is that i dont know how to ask what i am trying to understand from void, i would have to show you using a code as an example but i dont understand but because i dont understande void i cant do that. I know void does not return a function, but for example if i EXECUTE a code that contains a VOIDed function, what would i have to do to see or know that the function i voided was voided. like what would the program do or not do? i keep reading blinks post like he kinda gets what i am after.
Last edited on
Execution of a program means execution of statements of its functions. It is not important whether some function has return type void or something else. It is important that its statements will be executed.
Last edited on
what would i have to do to see or know that the function i voided was voided.


This line tells me your thought process is entirely wrong. A function is not "voided".

Forget everything you think you know about void functions, because I think you're thinking the wrong thing.


To understand it, it's really understanding the concept of a return type. So before you look at a function that returns void, let's look at one that returns an int:

1
2
3
4
5
6
7
8
9
10
11
// a function which adds two numbers and returns the result
int add(int a, int b)  // <- since 'add' is declared as an int...
{
    return a + b;  // <- we must return an int...
}

int main()
{
    int sum = add(3,5);  // <- the int we returned gets assigned to our 'sum' variable
    cout << sum;  // prints '8'
}


The return type of our add function is an int. This means the value we return from the function will be an int.

When we assign the function call to another variable (as we are doing on line 9), we can do that because the compiler knows that the add call will resolve to an int because that's its return type. Therefore we can assign it to another int... such as our sum variable.


Basically the return value is a convenient way to output data from a function.


With that in mind... all void means is that the function doesn't return anything. IE: the function doesn't have any output. The function can still perform work and do stuff... it just won't give anything back to the calling code.

here's an example:

1
2
3
4
5
6
7
8
9
10
11
void print(int val)  //<- void means "we're not returning anything"
{
    cout << val;
    //  <- nothing to return here because this is a void function
}

int main()
{
    print( 15 );  // outputs '15'
       // <- don't need (and can't) assign print() to anything because it didn't return anything
}


Here, our print has no feedback to give -- It just prints the data it's given. So there's no reason to return anything. Therefore it makes sense for this function to be a void.
Last edited on
I keep seen the terms void and voided used as though it was a verb, an action which does something. If so, its a misunderstanding.

let's say we have several functions like this:
1
2
3
4
float func1();
int func2();
void func3();
double func4();

Does it make sense to say that func1 has been floated, or func4 has been doubled?

No, it's nonsense. In the same way, to attempt to say that a function is voided is just as meaningless.

void is not an action, it's a type.

Last edited on
@Chervil I agree and I don't understand why it happens so much either. It's like an epidemic. I've noted it before but people have said it makes little difference; I think it seriously impacts their understanding of return values.
@LB I wondered whether it was something to do with the way the subject is being taught, either in a formal course, or in some book or online source.
http://tinyurl.com/GoogleVoidFunction
It's certainly an epidemic, but all references seem to be from questions of people calling it that. Whats worse is that the same terminology is used as a response/answer :(

I really hope it is not being taught that way somewhere. I have definitely heard my Java CS teacher say "void function" when teaching before, and I have pointed it out to him and he has corrected himself.
@Disch


so far you have answered what i was looking for, but in your 2nd example why would you have to put

1
2
3
4
5
6
7
8
9
10
11
12
13
void print(int val) 
{
    cout << val;
    //  <- nothing to return here because this is a void function "so why would you write this line? 
//why not just write print(15) in the main function?
// like what would be the point of cout<<val;?
}

int main()
{
    print( 15 );  // outputs '15'
       // <- don't need (and can't) assign print() to anything because it didn't return anything
}


this is new to me so thank you for having the patience, but you were the only one that explained it in a way i could understand i guess you were right in explaining the int function first and using an example. thank you
Last edited on
Obviously in that example there is no reason to use functions at all, but consider this example:
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 Pause()
{
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    //would you want to write this over and over again?
}

int main()
{
    cout << "Hello, and welcome to the Aperture Science Enrichment Center." << endl;
    Pause();
    string name;
    cout << "Please tell us your name: " << flush;
    getline(cin, name);
    cout << "Hello, " << name << ". We will begin the testing when you are ready." << endl;
    Pause();
    cout << "What is 2+2?" << endl;
    int n;
    cin >> n;
    if(n == 4)
    {
        cout << "Everyone in <subject hometown here> must be proud." << endl;
    }
    else
    {
        cout << "I hate you so much." << endl;
    }
    Pause();
    //...
}
Would you really want to write that long statement over and over again? What if you needed it change it, would you realy want to go through and change it everywhere?

The point of functions is to simplify programs and make it easier to modify them. The return type is unimportant - it just so happens that in this case we don't need to return anything, so we use a return type of null.
ok i want to thank everybody for helping me. I think im getting the hang of void. so for example if i wanted to do this in my code

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
30
31
32
33
34
35
36
37
38
using namespace std;

void title (string firstname, string lastname)
{
	cout << "Please enter your first name : " ;
		cin >> firstname;
	cout << "Please enter your last name : ";
		cin >> lastname;
}
void show(string name1, string name2)
{
	cout << "You entered " << name1 << "," << name2; //in this line
//i want the variables to show the firstname entered and the lastname entered, but 
//in the output it only shows "you entered , ".
// I thought that the variables from the main
//temporarily stored values into the function parameter and then uses them in the 
// function type.  so what did i do wrong?
}


int main()
{
	
	string go, stop;
	

	cout << endl;
	cout << setw(48) << "What's your name?";
	cout << endl;

	title (go, stop);// this function works
	cout << endl;
	show (go, stop);//but this one doesnt, it only shows the words "you entered" 
// and the comma ","

	getch();
	return 0;
}


after i looked at the code for a while im guessing it does not work because the cin is in the first function but the not the second so how would i get the second function to work?
Last edited on
Change line 3 to void title (string &firstname, string &lastname).

You should read up on the differences between passing by reference and passing by value.

http://www.cplusplus.com/doc/tutorial/functions2/
Pages: 12