-
April 5th, 2002, 05:04 PM
#1
Global/Local Variables
I have the following code:
#include <iostream.h>
double area;
double Area(double);
const double pi=3.14;
double radius=5;
int main()
{
cout<<"This Program Calculates The Area of a Circle \n";
area=Area(radius);
cout <<"The Area of the Circle is: "<<area<<endl;
cout<<"The Radius In the Main() Function is: "<<radius<<endl;
return 0;
}
double Area(double radius)
{
area = (pi*radius*radius);
double radius = 2;
cout<<"The Radius In the Area() Function is: "<<radius<<endl;
return area;
}
I get an error saying "error C2082: redefinition of formal parameter 'radius'"
Why can't I define a local variable in this manner?
'Grat is not nice, indeed!
-
April 5th, 2002, 07:05 PM
#2
Re: Global/Local Variables
The problem is purely in the second routine. You are declaring radius as the function parameter, and also within the body of the function. Both of these are being declared local to the routine - this is not allowed.
Hope this helps,
- Nigel
-
April 5th, 2002, 07:40 PM
#3
Re: Global/Local Variables
So how can I modify my code to keep the global variable radius as 5, and also make a local variable in the Area function?
'Grat is not nice, indeed!
-
April 5th, 2002, 07:51 PM
#4
Re: Global/Local Variables
double Area() // look ma, no hands (or parameter)
{
area = (pi * ::radius * ::radius); // using global radius (twice)
double radius = 2; // local variable only
cout<<"The Radius In the Area() Function is: "<<radius<<endl; // local again
return area; // was calculated based on global
}
If you want to access a global variable (or routine) from within a function, use the :: global scope modifier.
Hope this helps,
- Nigel
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|