Home > Back-end >  Confused by local scope and function Parameters
Confused by local scope and function Parameters

Time:08-18

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

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.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related