You are on page 1of 3

Compiler Design Lab

Lab 4: Symbol table construction

Name: Harisankar R N R
Reg No: 21BRS1524

Symbol Table Implementation using C++ with Hashtable / Unordered Map data
structure to represent the symbol Table.

Code with default I/o:


#include <iostream>
#include <unordered_map> // HashTable
#include <string>

using namespace std;

struct Symbol {
string type;
int value;
};

class SymbolTable {
private:
unordered_map<string, Symbol> table;

public:
void add_symbol(const string& symbol, const string& symbol_type, int value
= 0) {
if (table.find(symbol) == table.end()) {
Symbol new_symbol = {symbol_type, value};
table[symbol] = new_symbol;
cout << "Symbol '" << symbol << "' added to the table.\n";
} else {
cout << "Symbol '" << symbol << "' already exists in the table.
Use update_symbol() to modify it.\n";
}
}

void update_symbol(const string& symbol, const string& symbol_type, int


value = 0) {
if (table.find(symbol) != table.end()) {
Symbol updated_symbol = {symbol_type, value};
table[symbol] = updated_symbol;
cout << "Symbol '" << symbol << "' updated in the table.\n";
} else {
cout << "Symbol '" << symbol << "' does not exist in the table.
Use add_symbol() to add it.\n";
}
}

void delete_symbol(const string& symbol) {


if (table.find(symbol) != table.end()) {
table.erase(symbol);
cout << "Symbol '" << symbol << "' deleted from the table.\n";
} else {
cout << "Symbol '" << symbol << "' not found in the table.\n";
}
}

void search_symbol(const string& symbol) {


if (table.find(symbol) != table.end()) {
cout << "Symbol '" << symbol << "' found in the table with type: "
<< table[symbol].type
<< " and value: " << table[symbol].value << "\n";
} else {
cout << "Symbol '" << symbol << "' not found in the table.\n";
}
}

void display_table() {
cout << "\nSymbol Table:\n";
for (const auto& entry : table) {
cout << entry.first << " | Type: " << entry.second.type << " |
Value: " << entry.second.value << "\n";
}
cout << "\n";
}
};

int main() {
SymbolTable symbol_table;

symbol_table.add_symbol("x", "int", 10);


symbol_table.add_symbol("y", "float", 3.14);
symbol_table.add_symbol("z", "string");

symbol_table.display_table();

symbol_table.search_symbol("y");
symbol_table.update_symbol("y", "int", 5);
symbol_table.display_table();

symbol_table.delete_symbol("x");
symbol_table.display_table();

symbol_table.search_symbol("x");

return 0;
}

Screenshot of output tab:

A clear view of output with code comparison:

You might also like