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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With