Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pre-processor macro expansion

I'm trying to do (what I would have thought) was a simple macro expansion

#define CLEAR_DIGIT(a,b)    iconMap[a] &= ~(b)
#define R1 4, 16
CLEAR_DIGIT(R1);

Now I would expect that to expand to CLEAR_DIGIT(4,16) which expands to iconMap[4] &= ~16 However, it doesn't... If I make CLEAR_DIGIT a function:

void ClearDigit(unsigned char a, unsigned char b)
{
    iconMap[a] &= ~b;
}
#define R1 4, 16
ClearDigit(R1);

then it works fine, so R1 being expanded out to the two arguments isn't an issue... Is there any way of forcing it to expand R1 before doing the macro function expansion?

like image 619
Mike Hudgell Avatar asked Dec 21 '11 09:12

Mike Hudgell


People also ask

What is macro expansion in preprocessor?

The LENGTH and BREADTH are called the macro templates. The values 10 and 20 are called macro expansions. When the program run and if the C preprocessor sees an instance of a macro within the program code, it will do the macro expansion. It replaces the macro template with the value of macro expansion.

What do you mean by macro expansion in C?

A macro consists of name, set of formal parameters and body of code. The use of macro name with set of actual parameters is replaced by some code generated by its body. This is called macro expansion.

What handles macro expansion in C?

The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.

What does a preprocessor macro do?

The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled. These transformations can be the inclusion of header files, macro expansions, etc.


1 Answers

You could use a helper macro. See also double-stringize problem

#define CLEAR_DIGIT_HELPER(a,b) iconMap[a] &= ~(b)
#define CLEAR_DIGIT(x) CLEAR_DIGIT_HELPER(x)
#define R1 4, 16
CLEAR_DIGIT(R1);
like image 87
Benoit Avatar answered Sep 28 '22 20:09

Benoit