c - How to reuse a literal in a char and a one-character string constant? -
i need specify argument short option (e.g. -f
) both char
, char[]
constant in c code. in order maximize code reusage want declare variable allows me change value in 1 place (a "literal" - not stringly speaking string or char
literal, in sense of abstract concept). prefer solution solves exclusively in preprocessor constants , functions/macros or exclusively in c code explanation why has solved in mixture of both.
i tried/checked out
- to
#define foreground_option_value 'f'
causes me trouble transformchar[]
(as preprocessor constant) (writing macro stringifies#
causes'
quotes stringified well - to omit
'
quotes leaves me problem of creating'
quotes or createchar
way. - @pedrowitzel's answer declare
char[]
, use 0thchar
constant. that's fine, i'd prefer way createchar[]
char
because enforces both equal (otherwise i'd have add compile time assertionchar[]
isn't longer1
).
the thing matters me code maintenance, nothing else (like cost in processing code (during compilation or runtime - have not reflected intensively if there , don't care)).
over , above discussion in comments pedro witzel's answer, there's option:
#define foreground_option_value 'f' static const char fg_opt_str[] = { foreground_option_value, '\0' };
it's not commonly used way of initializing string, valid 1 , seems appropriate scenario. can use foreground_option_value need constant char
(or int
) value, , fg_opt_str
need one-character string. if change value defined (to f
, say), have change 1 place code continue work, assuming weren't using f
before, meets maintainability requirement.
Comments
Post a Comment