Reputation: 455
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
Upvotes: 4
Views: 11080
Reputation: 516
I copied-pasted your code. Just made a small change to the function call. It gives me output as desired.
Change: Instead of &buffer, pass buffer
//MapFormattToString(myformat,&buffer);
MapFormattToString(myformat, buffer);
Here is the main function for your reference:
int main()
{
char buffer[50];
/* other code and variables */
/* somewhere later in code */
Format myformat = BLUE;
/* later calling format function */
//MapFormattToString(myformat,&buffer);
MapFormattToString(myformat, buffer);
// MapFormattToString(0x64, buffer);
printf("\n***** Buffer = %s\n", buffer);
}
Compiler used: gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Upvotes: 0
Reputation: 18962
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);
}
Upvotes: 4
Reputation: 13510
In MapFormatToString
try printing the value inside format:
printf("%x", format);
If you don't get 64 (0x64, that is), it means something went wrong between the assignment to format and reading it inside MapFormatToString
. For example, if an enum is treated as 32 bit integer, something might happen to it when converting uint8.
Also, try not passing buffer at first, only print the value of format.
Upvotes: 0