enums in switch case

c, enums

Solution

I just wrote the following program, compiled it, and tested it, and the output is:

$ ./test
    d
    e

$

which is exactly what you'd expect. Hope this helps you spot some difference in your program.

#include<stdio.h>

typedef unsigned char uint8_t;

typedef enum {
    RED = 0x64,
    GREEN = 0x65,
    BLUE = 0x87
} Format;

void MapFormatToString(uint8_t format, char *buffer) {
    switch (format) {
        case RED:
            sprintf(buffer, "%c\n", RED);
            break;
        case GREEN:
            sprintf(buffer, "%c\n", GREEN);
            break;
        case BLUE:
            sprintf(buffer, "%c\n", BLUE);
            break;
        default:
            sprintf(buffer, "Unknown\n");
    }

}

main (int argc, char *argv[]) {
    char buffer[100];

    MapFormatToString(RED, buffer);
    printf(buffer);
    MapFormatToString(GREEN, buffer);
    printf(buffer);
    MapFormatToString(BLUE, buffer);
    printf(buffer);
}

Problem

What's wrong with this piece of code: ``` #define str(x) #x #define xstr(x) str(x) typedef unsigned char uint8_t; typedef enum { RED = 0x64, GREEN = 0x65, /* other enum values */ BLUE = 0x87 } Format; char buffer[50]; /* other code and variables */ /* somewhere later in code */ myformat = RED; /* later calling format function */ MapFormattToString(myformat,&buffer); void MapFormattToString(uint8_t format,char *buffer) { printf("format = %x\n",format); /*format printf has output 64 */ switch(format) { case RED: sprintf(buffer,"%s\n", xstr(RED)); break; case GREEN: sprintf(buffer,"%s\n", xstr(GREEN)); break; case BLUE: sprintf(buffer,"%s\n", xstr(BLUE)); break; default: sprintf(buffer,"Unsupported color\n"); } } ``` If I step through this function with myformat = RED , it does not fall through any of the cases but instead falls through default in the switch case. My objective is to that buffer should have RED in it instead of it's corresponding enum value i.e 64. Compiler : gcc 3.4.5 on Windows XP

Original source