Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Parentheses in Define Preprocessor Statements

So I was wondering when is to use

 #define xxx (yyy)

vs

 #define xxx  yyy

My project includes a files that has its own defines such at AD0_ADMD_CT if I wanted to redefine them would I need to use (AD0_ADMD_CT) or just AD0_ADMD_CT in the define or not?

AD0_ADMD_CT is a defined as

 #define    AD1_ADMD_CT     (IO_AD1.ADMD.bit.CT)

So it would be either

#define AD0_COMPARETIME     (AD0_ADMD_CT)

or

#define AD0_COMPARETIME     AD0_ADMD_CT
like image 755
Chrusciki Avatar asked Mar 03 '14 19:03

Chrusciki


4 Answers

There is no difference in both. In first case XXX is replaced by yyy and by (yyy) is second case. The convention to use brackts is to avoid logical errors that may occur. For example you define addition function as:

#define f(N) N+N 
int a = f(5)*f(5)  

Expected value is 10*10 = 100 , but output is 35 because at compile time is becomes

int a = 5+5*5+5, so using operator preference rule, output changes.

So parenthesis avoid these type of errors.

like image 140
Shashwat Kumar Avatar answered Oct 16 '22 18:10

Shashwat Kumar


By adding parentheses, you are forcing the argument inside the parentheses to be evaluated before the rest of the macro body, so if you had

#define MULT(x, y) (x) * (y)
// now MULT(3 + 2, 4 + 2) will expand to (3 + 2) * (4 + 2)

It does not appear to affect your current case unless there is more to your macros.

like image 43
Engineer2021 Avatar answered Oct 16 '22 18:10

Engineer2021


It's very important if you have operators in your macro. For example:

#define ADD(x,y) x + y
ADD(1,2) * 3 /* Should be 9, is 7 */

Should be:

#define ADD(x,y) (x + y)
ADD(1,2) * 3 /* 7 */

These precedence problems also apply for the arguments, as @Gi Joe says, and need to be wrapped in parens for precedence.

However, for a macro like:

#define MAGICNUM 3

It doesn't matter.

like image 23
Linuxios Avatar answered Oct 16 '22 17:10

Linuxios


An important thing to remember is that the preprocessor simply expands macros. For example, if you had the following lines:

#define AD0_COMPARETIME_1    (AD0_ADMD_CT)
#define AD0_COMPARETIME_2    AD0_ADMD_CT

num_1 = AD0_COMPARETIME_1;
num_2 = AD0_COMPARETIME_2;

After the first expansion you'd have this:

num_1 = (AD0_ADMD_CT);
num_2 = AD0_ADMD_CT;

And after the second expansion you'd have this:

num_1 = ((IO_AD1.ADMD.bit.CT));
num_2 = (IO_AD1.ADMD.bit.CT);

A problem may arise, as stated in other answers, when an expression is expanded.

like image 1
Fiddling Bits Avatar answered Oct 16 '22 16:10

Fiddling Bits