Sujet : Re: Concatenated if and preprocessor
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 13. Mar 2025, 17:30:47
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250313092153.666@kylheku.com>
References : 1
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2025-03-13, pozz <
pozzugno@gmail.com> wrote:
Consider this code:
>
if (cond1) {
...
} else if (cond2) {
...
} else if (cond3) {
...
}
>
I want to activate every single if with a macro preprocessor. All the
combinations are possible: only the first, only the second, only the
third, the first and second... and so on.
>
What's the best method to have a clean code that is always compiled
without errors?
The best way is not to use the preprocessor to try to conditionally
generate syntax. Rather, use the preprocessor to control the
conditions. You can make the conditions appear false at compile
time, and he compiler will remove the code as dead code.
#if HAVE_FEATURE_RELATED_TO_COND1
#define cond1 real->expression[0].fun(arg)
#else
#define cond1 0
#endif
Thus if the feature is disabled, then if (cond1) becomes if (0).
There are reasons why this might not work, like the associated
code not compiling when the feature is disabled, due to missing
declarations.
Suppose we have to use the preprocessor to remove any combination of the
conditionals.
Firstly, let's (1) start the if/else ladder with a dummy if that is
always false, and (2) terminate it with a dummy else.
That way everything in between is consistenlty an "else if" item.
if (0) { /* empty */ }
else if (cond1) { ... code ...}
else if (cond2) { ... code ...}
else if (cond3) { ... code ...}
else { /* empty */ }
You see where this is going? We can now delete any combination of the
conditionals, including all of them.
if (0) { /* empty */ }
##if HAVE_FEATURE_REALTED_TO_COND1
else if (cond1) { ... code ...}
#endif
##if HAVE_FEATURE_REALTED_TO_COND2
else if (cond2) { ... code ...}
#endif
##if HAVE_FEATURE_REALTED_TO_COND2
else if (cond3) { ... code ...}
#endif
else { /* empty */ }
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca