CodeBlanks Logo Icon CodeBlanks

Symbol table

Learn the symbol table and its management.

What is a symbol table?

A symbol table is the data structure where the compiler stores identifiers (variables, functions, types) by name. Each symbol carries name, type, scope and location.

When the lexer sees an identifier it checks the table; if absent it inserts. The parser and codegen use the table for type checking and address generation. A common implementation is a hash table or a linked list; to support scopes each scope holds its own table. When a variable leaves scope its table is dropped. The symbol table is the compiler's memory; its consistency decides compile success.

lookup and insert

The table has two core operations: lookup searches by name, insert adds a new symbol. Both are called throughout parsing and codegen.

On a declaration you call insert; on a use you call lookup. If lookup returns empty you raise an undefined-variable error. To support scopes the table is managed like a stack: a new scope opens a new table; when the scope ends its table is popped. In nested scopes the inner table is searched first, then the outer one. This makes shadowing work correctly.

Practice Print the symbol table

Define struct symbol { const char *name; int type; }. Define void print_symbol(struct symbol s) with body printf("%s:%d\n", s.name, s.type);. In main build a three-element struct symbol table[] array: {"x", 0}, {"y", 1}, {"sum", 2}. Loop with for and print each with print_symbol.

Starter code

main.c
#include <stdio.h>

// Define symbol struct
// Build a three-element table and call print_symbol in a for loop

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

struct symbol { const char *name; int type; };

void print_symbol(struct symbol s) {
    printf("%s:%d\n", s.name, s.type);
}

int main(void) {
    struct symbol table[] = {
        {"x", 0},
        {"y", 1},
        {"sum", 2}
    };
    int n = sizeof(table) / sizeof(table[0]);
    for (int i = 0; i < n; i++) {
        print_symbol(table[i]);
    }
    return 0;
}

Expected output

x:0
y:1
sum:2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a symbol table store?

  • Name and info Correct answer
  • Only value
  • Only address
  • Only type

Explanation: A symbol table keeps identifier names and attributes together.

2 Match symbol table concepts

Term Meaning
symbol Name and info
scope Access region
lookup Search
insert Add

3 Complete the symtab lookup call

Question
int type = symtab_____(name);
Answer
int type = symtab_lookup(name);

Explanation: lookup searches for a symbol by name.

All lessons in Expert