Search code examples
cenumsmacrosconstantsenumeration

How compiler handles symbolic constants in enumerations?


If we talk about macros than compiler handles them during preprocessing stage but what about enumerators. How compiler sees them. For example see the below code :

#include <stdio.h> 
enum day {sunday = 1, monday, tuesday = 5, 
        wednesday, thursday = 10, friday, saturday}; 

int main() 
{ 
    printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, 
            wednesday, thursday, friday, saturday); 
    return 0; 
} 

In this particular example, I have not even created any variable for enumerated data type. I am simply using the enumeration-constants in my printf() statement. Do enumerators work similar to macros internally ? Will all these symbolic constants be replaced by there integer constants during preprocessing ? How exactly compiler handles them ?


Solution

  • Do enumerators work similar to macros internally ?

    Somewhat yes, somewhat no.

    Will all these symbolic constants be replaced by there integer constants during preprocessing ?

    No. The preprocessor does not know one identifier from another, except those of preprocessing directives, the defined operator, and defined macro names. You could try this:

    #include <stdio.h>
    
    #define MACRO_TRUE 1
    enum bool_enum { ENUM_FALSE = 0, ENUM_TRUE = 1 };
    
    int main(void) {
    #if MACRO_TRUE
        puts("Macro identifiers are known to the preprocessor.");
    #else
        puts("Macro identifiers are not known to the preprocessor.");
    #endif
    #if ENUM_TRUE
        puts("Enum constants are known to the preprocessor.");
    #else
        puts("Enum constants are not known to the preprocessor.");
    #endif
    }
    

    The output should be

    Macro identifiers are known to the preprocessor.
    Enum constants are not known to the preprocessor.
    

    How exactly compiler handles them ?

    In-scope enum constants are similar to other integer constants, such as 42, except for the above caveat that they are not interpreted as such by the preprocessor. They can be used in integer constant expressions, for example, which are required for various purposes such as in case labels in switch statements. The standard does not specify details, but most compilers treat them similarly to macros in that no storage is reserved in the executable for them -- the source is treated as if enum constants were replaced by their corresponding integer values wherever they appear in expressions, after pre-processing. Certainly they do not identify objects, in that they are not acceptable operands of the & operator.

    This is to be distinguished from the behavior of const-qualified variables. These identify actual objects, not mere constants. They may not be used in constant expressions, and they do have storage associated with them (in the abstract machine, at least), so their addresses may be obtained via the & operator.