C Macro Filter String literals in arguments

Is it possible to do a parse or filter in C a macro for example:

FILTER(Var, "text", somevar, foo, "moretext")

Becomes or expands to:

FILTER(Var, somevar, foo )


Old question:

INPUT(sometext <name1> sometext somemoretext <name2> moretext here)

and expands to a macro statement:

FILTER(<name1><name2>)

it just parse and retains the text enclosed in <> and ignores the rest.
Last edited on
No, macros can't do text processing like that.
Ok well how about ignore args that are
string literals in quotes?

So

FILTER(Var, "text", somevar, foo, "moretext")

Becomes or expands to:

FILTER(Var, somevar, foo )

I have updated my topic to reflect my use case
Since the old one is not possible.
Last edited on
Again no.

You can change an argument to a quoted literal, but you can't go the other way.
Macros don't provide any way to test if an argument is a quoted literal.
Last edited on
Why not
#define IGNORE(...)
Then
WHATEVER_YOU_WANT(a, b, IGNORE(c), d)

Thanks, but what i'm after is to first check whether the arg is a string literal.
Can't be done, I'm afraid. You could look into passing the source through M4 before compiling. The M4 syntax is similar to the C preprocessor's.
https://www.gnu.org/software/m4/manual/m4.html
If you're going that route, though, you're probably better off just writing a small program that generates your source. Maintaining M4 input sucks.
The problem is that string literals are typically treated as being self-delimiting. This means that the normal pattern matching hack used to identify particular tokens can't work with double quotes.

Here's an example of the trick. Here the macro IS_DQUOTE expands to 1 if you pass in the word dquote but otherwise it expands to 0:
1
2
3
4
5
6
7
8
9
#define CONCATENATED0(a, ...) a##__VA_ARGS__
#define CONCATENATED(a, ...) CONCATENATED0(a, __VA_ARGS__)
#define SECOND(a, b, ...) b
#define IS_DQUOTE_PATTERN_dquote _, 1
#define IS_DQUOTE0(...) SECOND(__VA_ARGS__, 0)
#define IS_DQUOTE(a) IS_DQUOTE0(CONCATENATED(IS_DQUOTE_PATTERN_, a))

static_assert(IS_DQUOTE(dquote))
static_assert(IS_DQUOTE(anything else) == false)
https://coliru.stacked-crooked.com/a/404abcb9a144df9e

When trying to adapt this to identify actual quoted strings, the most immediate problem is that
CONCATENATED(IS_DQUOTE_PATTERN_, "")
is a syntax error.
This can be worked around by abusing UDL suffixes:
CONCATENATED("", _x_INVENTED_UDL_SUFFIX)()
But it still doesn't help because it appears that the resulting expansion, which is ""_x_INVENTED_UDL_SUFFIX(), won't expand even if _x_INVENTED_UDL_SUFFIX is a function-like macro.

Some alternatives might be:
WHATEVER_YOU_WANT(a, b, STRINGIFY(xyz), d)
or
WHATEVER_YOU_WANT(a, b, DQUOTE, c, DQUOTE, d)
or
WHATEVER_YOU_WANT(a, b, DQUOTE c DQUOTE, d)

Also, depending on what code is generated you might be able to use templates to do it.

Last edited on
Topic archived. No new replies allowed.