Home > Net >  Is there a technical reason why an enumerator is not a literal?
Is there a technical reason why an enumerator is not a literal?

Time:11-06

I thought that the enumerators of an enum [class] were literals, because, to my understanding, they represent for their enum [class] what 1 represents for int, true for bool, and "hello" for char const*. However, they are not, because the standard lists only these literals,

literal:
    integer-literal
    character-literal
    floating-point-literal
    string-literal
    boolean-literal
    pointer-literal
    user-defined-literal

whereas the word literal doesn't occur at all in [dccl.enum].

Is there a reason why the standard doesn't classify enumerators as literals of the enumeration type they belong to?

CodePudding user response:

Is there a technical reason why an enumerator is not a literal?

You'll notice that the term "literal" is defined in the C standard chapter "Lexical conventions". "Lexical" here refers to Lexical analysis, which takes a sequence of characters and generates a sequence of tokens. These tokens then undergo grammatical processing.

C defines various classes of tokens. Among these are keywords, operators, punctuation, identifiers, and yes literals. But that's all a literal is: a kind of token. A classification of the lexical analysis of a sequence of characters.

An enumerator is not the product of lexical analysis of characters; it's the product of syntactic analysis of a sequence of tokens. Consider this sequence of text: name1::name2. Lexically, you know what this is: it's an identifier followed by the :: operator, followed by an identifier.

Grammatically however... you have no idea. Maybe name1 designates a class and name2 is a member of that class. Maybe name1 is a namespace and name2 is a member of that namespace. Or... maybe name1 is an enumeration and name2 is an enumerator within that enumeration.

You cannot know just from the sequence of text in isolation. Syntax is a matter of context, and without context, all you have is a bunch of tokens.

An enumerator cannot be a literal because the determination of what is or is not an enumerator is a product of a process that happens after the determination of what is and is not a literal.

  • Related