Using parentheses in the definition of preprocessor statements

So I was wondering when to use

 #define xxx (yyy)

vs

 #define xxx  yyy

My project includes files that have their own definitions, such as AD0_ADMD_CT, if I want to override them, will I need to use (AD0_ADMD_CT) or just AD0_ADMD_CT in the definition or not?

AD0_ADMD_CT is defined as

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

So it will be either

#define AD0_COMPARETIME     (AD0_ADMD_CT)

or

#define AD0_COMPARETIME     AD0_ADMD_CT
+4
source share
4 answers

There is no difference in both. In the first case, it XXXis replaced by yyy, and by (yyy)- the second case. An agreement to use braces is to avoid logical errors that may occur. For example, you define the add function as:

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

10 * 10 = 100, 35,

int a = 5+5*5+5,, , .

, .

+5

, , ,

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

, .

+3

, . :

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

:

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

, @Gi Joe, parens .

:

#define MAGICNUM 3

.

+2

, . , :

#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 extension, you will receive the following:

num_1 = (AD0_ADMD_CT);
num_2 = AD0_ADMD_CT;

And after the second extension, you will have the following:

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

A problem can occur, as indicated in other answers, when expanding an expression.

0
source

Source: https://habr.com/ru/post/1529875/


All Articles