#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int e=0;
int b=0;
cout<<"Enter Exponent";
cin>>e;
cout<<"Enter Base";
cin>>b;
pow(e, b);
cout<<"Power:"<<e;
return 0;
}
void pow(int e, int b)
{
int t=1;
while(b==t)
{
e=e*b;
t++;
}
}
Here is the error I received:
ulaga.cpp|29|error: 'pow' was not declared in this scope
Can any one explain why this error occurred?
The C++ compiler parses through your code file sequentially in order. i.e. line 1 then line 2 then line 3… and so on. So by the time the compiler comes to the function call statement
pow(e, b);in yourmain()function, it hasn’t yet reached the definition of the functionvoid pow(int e, int b)below themain()function and therefore gives you the error. There are two ways to solve this.1) Move the definition of
void pow(int e, int b)(and any other function that you plan to call frommain()) above themain()function itself. This way the compiler has already parsed and is aware of your function before it reaches thepow(e, b);line in yourmain().2) The other way is to use a forward declaration. This means adding the line
void pow(int e, int b);before themain()function. This tells the compiler that the function given by the forward declaration (in this casevoid pow(int e, int b)) is defined in this code file but may be called before the definition code of the function in the file. This is a better method as you may have multiple functions in your file calling one another in different order and it may not be easy to rearrange their definitions to appear before they are called in a file. Here’s a good read on Forward DeclarationYou may also want to pass parameters by reference to your function to get the correct result. i.e. use
void pow(int& e, int& b). This will cause the values modified in yourpow()function to actually be applied to integerseandband not just to their copies which will be thrown away afterpow()is done executing. This link about passing arguments by reference in functions is pretty good at explaining this.