Re: String comparison in preprocessor commands
- From: Eric Sosman <eric.sosman@xxxxxxx>
- Date: Tue, 24 May 2005 17:51:44 -0400
Erik Leunissen wrote:
> L.S.
>
> How can I make certain code parts be compiled conditionally, depending
> on the definition of a macro such as:
>
> #define VERSION "2.3"
>
> Is it all right to do things like:
>
>
> #if VERSION == "2.3"
> ..../* conditionally compiled code */
> #endif
>
> #if VERSION != "2.3"
> ..../* conditionally compiled code */
> #endif
>
> #if VERSION > "2.3"
> ..../* conditionally compiled code */
> #endif
No, that won't work: The preprocessor can generate
string literals, but it can't actually work with strings.
(In particular, it can't compare them.)
What you *can* do, which may be satisfactory for some
purposes, is use the preprocessor to generate a compile-
time constant, test that value with `if' instead of `#if',
and rely on the compiler to eliminate dead code:
#define MAJOR (VERSION[0] - '0')
#define MINOR (VERSION[2] - '0')
if (MAJOR == 2 && MINOR == 3) { ... }
if (MAJOR != 2 || MINOR != 3) { ... }
if (MAJOR > 2 || (MAJOR == 2 && MINOR > 3)) { ... }
However, this trick will only work for executable statements;
you can't use it to "conditionally compile" declarations and
the like. Also, it will break pretty badly if VERSION ever
becomes "2.10" or "10.0" ...
> Or should I go about this differently? Please note that I'm not in the
> position to change the macro definition.
If you really cannot change the macro definition, things
are going to be messy. The best I can suggest is to use a
"helper" program as suggested by Anonymous 7843. (However,
note that his suggestion of converting VERSION to `double'
is not very robust; consider the "2.10" case. The '.' in
a version number is a field separator, not a decimal point.)
If you must leave VERSION's string-ness and value intact
but are allowed to change the way it's defined, things can
be lots easier. Instead of trying to extract MAJOR and MINOR
from VERSION, you could use MAJOR and MINOR as the "primary
sources" and derive VERSION from them:
#define MAJOR 2
#define MINOR 3
#define STRING(x) STR_HELPER(x)
#define STR_HELPER(x) #x
#define VERSION STRING(MAJOR) "." STRING(MINOR)
This gives VERSION the same value as before, but makes MAJOR
and MINOR available for straightforward preprocessor tests.
--
Eric.Sosman@xxxxxxx
.
- References:
- String comparison in preprocessor commands
- From: Erik Leunissen
- String comparison in preprocessor commands
- Prev by Date: Re: PLEASE..
- Next by Date: Querry (Newbe)
- Previous by thread: Re: String comparison in preprocessor commands
- Next by thread: Re: String comparison in preprocessor commands
- Index(es):
Relevant Pages
|