Recursive function giving me an error

I need to write a function that will recursively raise a number to a power. I have most of it down but i am receiving error C2601 during line 30.

Error 1 error C2601: 'power' : local function definitions are illegal

and also intllisense expected a ";"

thanks for any assistance!

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
39
40
//Chapter 19 programming challenge 6
//Recursive Power Function
//

#include <iostream>
using namespace std;

//function prototype 
int power(int, int);

int main()
{
	int base, exponent, product;

	//Ask user to input base number and exponent
	cout << " Please first enter the base and then the exponent. " << endl; 
	cin >> base >> exponent; 

	
	product = power(base, exponent);
	cout << " The solution to your power is: " << product << endl;
	return 0;


	//***************************************************************************
	//power to recursively determine the product of the power                   *
	//***************************************************************************

	int power(int number, int exponent)
	{
		if (exponent == 1) //base case
			return number;

		else if (exponent > -1)
			exponent--;

		return number* (power(number, exponent));
	}

}
Last edited on
Define power() outside of main.
Is this what you mean? I changed line 9 to:

int power(int base, int exponent);

i got a lot of errors saying the variables in my function were not defined.
No, I meant move lines 29-38 outside of the main function. i.e. remove the curly brace on line 40 and put it on line 23.
I feel so stupid for making such a silly mistake. I felt like it was going to be something like that too! Thanks for all your help shadowmouse!
Last edited on
Try running with base=10 and exponent=0. What should the answer be? What answer do you get?

Also, what about negative exponents? Hmm. The answer would a fraction, but you can't return that. A handy way to solve this is to change exponent to unsigned int so it's impossible to pass a negative exponent. Just be sure to change the code that compares it to -1!
Topic archived. No new replies allowed.