Search code examples
scopesymbol-table

symbol tables and scope


For the below code I"m trying to draw symbol tables for each scope. The scopes are global, f1, else, and f2. I was wondering if for f2, x would be considered a symbol of that scope. Also, does the f1(5) get associated with any symbol tables?

int x = 3;
int f1(int x) {
    if (x > 4)
        f1(x-1);
    else { 
        int x = 1; f2();
    } 
}
int f2() {
    print x; 
}
f1(5);

Solution

  • Working with some general assumptions about scoping and variable declarations.

    1. Not as such. A symbol is only added to the symbol table when it is declared. Since you're only using x it won't be added to any table. So your question sort of doesn't make sense. Your compiler would encounter the use of symbol x and look it up in the symbol table. It would be found as the x from the global scope.

    2. The f1(5) isn't really associated with any symbol tables. Since you're making a function call you'll have to look up f1 to make sure it exists (and parameter numbers/types match). You'll find f1 in the symbol table at the global scope since it has already been defined before the use (also, since the code at that point only has one scope, global, there is only one table to look at). So f1(5) is associated only in the fact that you'll find the f1 symbol and the parameter information in the symbol table.