Question about return statements in a void function

Hi all,

I'm trying to wrap my head around void functions, and the only part that I'm unsure about is the return statement. The book I'm reading gives the following example, and explanation:

void echoSquare()
{
int value;
cout << "Enter a value: ";
cin >> value;
cout << "\nThe square is: " << (value * value) << "\n";
return;
}

Explination from book:
Control begins at the open brace and continues through to the return statement. The return statement in a void function is not followed by a value. The return statement in a void function is optional. If it isn't present, execution returns to the calling function when control encounters the close brace.

Question:
Does this mean (with this example), that when the user enters a value (i.e. 10) the value of 100 would not be shown because "the return statement in a void function is not followed by a value"?
Last edited on
No, the function will do whatever its going to, it just wont return any value to int main(). Cout is it's own thing. Within the void function, you're going to print to the screen. Whether or not you return something means nothing in terms of what the program will output in this case.

Return values matter in cases like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int echoSquare()
{
	int value;
	std::cout << "Enter a value: ";
	std::cin >> value;
	std::cout << "\nThe square is: " << (value * value) << "\n";
	return (value * value);
}

int main() 
{
	int sqr = echoSquare();

	std::cout << "\nSqr = " << sqr;
}


Now we want a return value because we want to set "sqr" equal to the value that comes back.
This makes complete sense - thank you!
There can be a use for explicit return in void function:
1
2
3
4
5
6
7
8
9
10
11
12
void echoSquare()
{
  int value;
  cout << "Enter a value: ";
  cin >> value;
  if ( 1'000'000 < value ) {
    // will not square big numbers
    return; // we don't want to multiply and print
  }

  cout << "\nThe square is: " << (value * value) << "\n";
}
Topic archived. No new replies allowed.