Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused by local scope and function Parameters

Hello im confused by function parameters.
I’ve had a guy try and help me but i struggle to understand. I’ve been following learncpp

And local scope confuses me when it comes to parameters.

It says on learncpp, That if you declare a function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int foo(int x, int y) // int x and y are local

So How then can i access those parameters if it is local using a function.

Here is my code with what im struggling with.

double increaseSpeedControl(int Speed, int max) // int speed and int max are local
{ // local scope

    if (Speed <= 100)
    {
        int max{ 100 };
        while (Speed < max)
        {
            std::cout << "Increasing : " << Speed++ << std::endl;
        }
    }
    else
    {
        return 0;
    }
    return Speed;
} // end of scope 

int main()
{ // local scope
    std::cout << "Set Current Speed :";
    int sp{};
    std::cin >> sp;
    std::cout << "Speed Increased :" << increaseSpeedControl(sp, 100) << std::endl;
    std::cout << "Now : " << sp; 

 // How then am i able to access increaseSpeedControl(sp, 100) 
if inside the function is a local scope?


} // end local scope

This is really hard for me to grasp and i would appreciate some help.

>Solution :

From main‘s perspective, the function is a black box. The box has two holes labeled Speed and max. main inserts two int‘s and lets the box do its thing. Then the box spits out an int at the end for main. At no point can main see into that box to access Speed or max (those are local only to the box). main can only feed two values in and wait for one to be spat back out.

This is what we mean when we say that variables are "local." They exist only in the black box where no one outside of the scope can see them.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading