CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2001
    Location
    CA.
    Posts
    65

    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!

  2. #2
    Join Date
    Sep 2001
    Location
    San Diego
    Posts
    2,147

    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



  3. #3
    Join Date
    Oct 2001
    Location
    CA.
    Posts
    65

    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!

  4. #4
    Join Date
    Sep 2001
    Location
    San Diego
    Posts
    2,147

    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
  •  





Click Here to Expand Forum to Full Width

Featured