Skip to the content of the web site.

The scope of parameters and local variables

In Python, a parameter or local variable in a function can only be accessed within that function. The parameters are assigned values that are passed as arguments to that function, while local variables are assigned values in the function.

In C++, statements surrounded by braces (a { and a corresponding }. Parameters may be accessed by any statement within the block defining the function. For example, this is a function that calculates the greatest common divisor of two integers:

unsigned int gcd( unsigned int m, unsigned int n ) {
    // If m < n, swap 'm' and 'n'
    if ( m < n ) {
	unsigned int tmp{m};
        m = n;
        n = tmp;
    }

    while ( n != 0 ) {
	unsigned int r{m % n};  // 'r' is the remainder when m / n
        m = n;
        n = r;
    }

    return m;
}

we see that m and n can be accessed anywhere between the opening and closing braces that define the function body.

Additionally, if you look at the example, the local variable tmp is defined between two braces. That local variable can be accessed from where it was declared, and the corresponding closing brace. Thus, if you tried to access tmp after, the compiler would not allow this.

Similarly, the local variable r is defined within the body of the while look, and so cannot be accessed outside that block. If, for example, the user tried to return

    return m + r;

this would not be allowed because r is now out of scope.

In the example of the factorial function,

unsigned int factorial( unsigned int n ) {
    unsigned int result{1};

    for ( unsigned int k{2}; k <= n; ++k ) {
        result *= k;
    }

    return result;
}

Here, n is a parameter and is accessible anywhere within the function body. The local variable result is declared inside the function body, and is therefore accessible at any point until the end of that block. The local variable k is only accessible in the block associated with that loop.

It is generally good coding practice to only define local variables as close as you can to where it is first used in a fucntion body.