Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a macro remove characters from its arguments?

Is it possible to define a macro that will trim off a portion of the string argument passed in?

For example:

//can this be defined?  
#define MACRO(o) ???

int main(){
   printf(MACRO(ObjectT)); //prints "Object" not "ObjectT"
}

Would it be possible for a macro that trim off the last character 'T'?

like image 296
Trevor Hickey Avatar asked May 20 '16 19:05

Trevor Hickey


People also ask

How many arguments macro can have?

For portability, you should not have more than 31 parameters for a macro. The parameter list may end with an ellipsis (...).

Which is a valid type of arguments in macro?

There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.

What is macro argument in C?

macro (array[x = y, x + 1]) passes two arguments to macro : array[x = y and x + 1] . If you want to supply array[x = y, x + 1] as an argument, you can write it as array[(x = y, x + 1)] , which is equivalent C code. All arguments to a macro are completely macro-expanded before they are substituted into the macro body.

Can macro return a value?

Macros just perform textual substitution. They can't return anything - they are not functions.


2 Answers

You can do it for specific strings that you know in advance, presented to the macro as symbols rather than as string literals, but not for general symbols and not for string literals at all. For example:

#include <stdio.h>

#define STRINGIFY(s) # s
#define EXPAND_TO_STRING(x) STRINGIFY(x)
#define TRUNCATE_ObjectT Object
#define TRUNCATE_MrT Pity da fool
#define TRUNCATE(s) EXPAND_TO_STRING(TRUNCATE_ ## s)

int main(){
   printf(TRUNCATE(ObjectT)); // prints "Object"
   printf(TRUNCATE(MrT));     // prints "Pity da fool"
}

That relies on the token-pasting operator, ##, to construct the name of a macro that expands to the truncated text (or, really, the replacement text), and the stringification operator, #, to convert the expanded result to a string literal. There's a little bit of required macro indirection in there, too, to ensure that all the needed expansions are performed.

like image 168
John Bollinger Avatar answered Oct 17 '22 15:10

John Bollinger


Well, at least it should print "Object"...

//can this be defined?  
#define MACRO(o) #o "\b \b"

int main(){
    printf(MACRO(ObjectT)); //prints "Object" not "ObjectT"
}

And no, you can't strip character using preprocessor only without actual C code (say, malloc+strncpy) to do that.

like image 33
Matt Avatar answered Oct 17 '22 15:10

Matt