Enumerated types in C
Exercise: ABC Compiler Project
Write a new header file tokenkind.h that contains the following declarations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | enum TokenKind
{
EOI, // end of input
BAD_TOKEN,
HEX_LITERAL,
OCT_LITERAL,
DEC_LITERAL,
PLUS, // '+'
MINUS, // '-'
ASTERISK, // '*'
SLASH, // '/'
PERCENT, // '%'
EQUAL, // '='
LPAREN, // '('
RPAREN, // ')'
SEMICOLON, // ';'
IDENTIFIER,
};
const char *strTokenKind(enum TokenKind tokenKind);
|
Note: The phrase “Writing a header file with declarations ...” implicitly states to use proper include guards. It also implicitly means that eventually other header files need to be included. For example if the declarations use sizet you have to include stddef.h_.
Implement strTokenKind in tokenkind.c (do not forget to include the corresponding header file).
In the header lexer.h include tokenkind.h and change the declarations
1 2 | extern int token_kind;
int getToken(void);
|
to
1 2 | extern enum TokenKind token_kind;
enum TokenKind getToken(void);
|
After testing your changes make a new commit to your repository.
The Tag Namespace in C
Enumerated types in C belong to the so called tagged types. To this group also belong struct and union types. They were added later to C after the language was already in use. This meant that it was required to add these features without breaking existing code.