-1

i am a total newbie to c++. i am writing this function but somehow it give me this error

Error: a function-definition is not allowed here before '{' token

My code is

int main() {
    //number is given num
    // power is raise to power
    int raiseTo(int number, int power)
    {
        for (int i=0;i<=power;i++)
        {       
            number=number*number;
        }
        return number;
    }
}

Please tell me what i am doing wrong. thanks.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
Cloudboy22
  • 1,496
  • 5
  • 21
  • 39

2 Answers2

4

The C++ standard says:

§ 8.4.1/2 [..] A function shall be defined only in namespace or class scope.

So what you're doing is simply not allowed.

4

Two major problems:

  1. You should not implement a function inside a function
  2. You are not performing the power algorithm correctly

Try this code instead:

int raiseTo(int number,int power)
{
    int result = 1;
    for (int i=0; i<power; i++)
    {
        result = result*number;
    }
    return result;
}

int main()
{
    int x = 2;
    int y = 3;
    int z = raiseTo(x,y);
    printf("%d^%d = %d\n",x,y,z);
    return 0;
}
barak manos
  • 29,648
  • 10
  • 62
  • 114