C
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.
Exercise 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.
Show example solution
#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;
}
Test yourself
-
What does a symbol table store?
- Name and info
- Only value
- Only address
- Only type
Show answer
Name and info — A symbol table keeps identifier names and attributes together.
-
Match symbol table concepts
- symbol
- Name and info
- scope
- Access region
- lookup
- Search
- insert
- Add
-
Complete the symtab lookup call
int type = symtab_____(name);
Show answer
int type = symtab_lookup(name);
Next lesson: Summary - Compiler basics