Edit Anything

Professional text and hex editing
with Binary Templates technology.



SweetScape Knowledgebase

KB1025: How does scope work when defining local variables?

The scope of a variable refers to where in a template or script a variable can be accessed. A local variable (see KB1019 for more information) that is defined in the main program (not inside a function or structure) is called a global variable. Such a variable can be accessed anywhere in the template or script. However, things get more complicated when a local variable is defined within a struct. For example:

     struct {
        // Define a local variable
        local int ARRAY_SIZE = 5;
        
        struct {
            int ar[ARRAY_SIZE];  // ARRAY_SIZE can be accessed here
        } s1;
     } data;
     
     // The following line generates an ERROR 
     //   since ARRAY_SIZE cannot be accessed here
     Printf( "%d\n", ARRAY_SIZE ); 

In general, local variables can be accessed inside the struct they are defined in, and any other sub-structures defined inside that structure, but they cannot be accessed outside the structure.

One tricky area with scope is when functions are introduced into the picture, and this is where there is a difference between version 2.1 and 3.0 of 010 Editor. If version 2.1 and before, local variables inside a user-defined function could be accessed by structures defined inside the function; however, this behaviour caused some unexpected behaviour on some templates so it was removed in 3.0. For example, the follow template:

     struct DATA; 
     
     void my_function()
     {
         local int SIZE = 5;
         DATA r;
     }
     
     struct DATA
     {
         int range[SIZE]; // SIZE can be accessed in v2.1, but not in v3.0
     };
     
     my_function();

The variable SIZE can be accessed in the struct DATA in version 2.1 of 010 Editor, but not in version 3.0 (the template will not compile). In version 3.1, this problem will be solved by allowing structs to receive arguments so values can be passed into the struct. In 3.0, the only way to handle this issue is to assign the value of SIZE to a global local variable.





Newsletter - Receive special offers, tips, tricks and news. Join now



010 Editor v14.0.1 is here!
What's new?


Navigation


Products

010 Editor














E-mail: info@sweetscape.com