Search code examples
functionglobal-variablescapl

Overloading global variable in function


What is happening with global variable in CAPL, when it is initializing again in function or testfunction?

variables
{
    int i;
}

testfunction temp()
{
    int i = 0;
    for(i = 0; i < 10; i++)
    {
        // do something
    }
}

for(i = 0; i < 5; i++)
{
    temp();
}

Solution

  • In Variables section of CAPL, global variables are declared. Identifiers defined here have program scope. Global variable can be accessed by any function of your entire program after its declaration.

    variables
    {
        int xyz; // Identifier 'xyz' declared in an program scope
    }
    

    Second identifier is declared in an function scope and is not distinct form previous identifier. Function scope has more inner scope.

    void temp()
    {
        int xyz; // Identifier 'xyz' declared in an function scope 
        xyz=5;
        write("Inner scope -> d%",xyz);
    }
    

    CAPL has 'C like' scope rules set so: If two identifiers have the same name but different scope, the identifier in the inner scope hides the identifier in the outer scope.

    In this example, the object xyz in function temp hides the global variable xyz:

    on key * // call event
    {
      xyz=10;
      write("Outer Scope -> %d",xyz);  //  Program Scope
      temp();                          //  Function Scope
    }
    

    Output:

    • " Inner Scope -> 5 "
    • " Outer Scope -> 10 "