void function.

Hi guys,

I am working through Stroustrup's PPP and am trying to apply a function declaration to my code which is the answer to one of the "try this" exercises. This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  int square(int x)
{
	int result = 0;
	for (int i = 0; i < x; i++) {
		result += x;
	}
	return result;
}


int main()
{
	//int square(int);
	
	cout << "This program calculates squares. Enter a number: " << flush;
	int x = 0;
	cin >> x;

	cout << "The square of " << x << " is: " << square(x) << '\n';
	
	return 0;
}


When I uncomment the function call in my main()(int square(int);), I get all sorts of errors. I know I'm already calling square in my cout. However, I want to see how a function declaration of the form "int square(int);" would work in my code. Also I'd like to see if I can use int square() as a void function. What sort of changes would I need in order for this to work; I know I'd have to have no return value for starters.
When I uncomment the function call in my main()(int square(int);), I get all sorts of errors.

When I uncomment line 13, I get no errors. Line 13 is a legal function declaration with local scope. Local function declarations are not illegal, but function declarations should generally be global, not local.

I'd like to see if I can use int square() as a void function

You would have to have some way to return the result. If you make it a void function, your only choice is to make the result a reference argument. Also, if you make it a void function, you won't be able to use it in your cout statement.

Last edited on
Thanks very much, that's very helpful!!
Topic archived. No new replies allowed.