Is it possible to rewrite the following code, so I only need to change in one place if the line changes?
#define MY_STRING "Foo bar" #define MY_STRING_FIRST_CHAR 'F'
The following is not valid because it refers to char in a memory location, so it cannot be used as an example in a switch :
#define MY_STRING_FIRST_CHAR MY_STRING[0] switch (something) { case MY_STRING_FIRST_CHAR: break; }
The goal is to efficiently analyze the resulting string by looking at one character. In my case, all lines have one unique character. The following is not my actual code, but a very simple example to show the principle:
#define COMMAND_LIST "list" #define COMMAND_LIST_FIRST_CHAR 'l' #define COMMAND_CHANGE "change" #define COMMAND_CHANGE_FIRST_CHAR 'c' #define COMMAND_EXIT "exit" #define COMMAND_EXIT_FIRST_CHAR 'e' switch(received_command_string[0]){ case COMMAND_LIST_FIRST_CHAR:
User "pmg" found this in the gcc documentation: "Unable to convert macro argument to character constant".
I wanted the definitions to be in an include file that can be used by several source files. This is so close that I can get, but only each character defined in one place:
#include <stdio.h> #define CH0 'F' #define CH1 'o' #define CH2 'o' #define CH3 ' ' #define CH4 'b' #define CH5 'a' #define CH6 'r' static char MY_STRING[] = { CH0, CH1, CH2, CH3, CH4, CH5, CH6, '\0'}; #define MY_STRING_FIRST_CHAR CH0 void main(void){ printf("The string is %s, the first char is %c\n", MY_STRING, MY_STRING_FIRST_CHAR); }
I will not do it. The initial question was whether one definition could be used to get both a string constant and a character constant. Due to the loss of clock cycles at run time, there are several solutions to my problem.