1

I can make sense of this:

#define ADD( f1, f2 ) ( (f1) + (f2) )

And I guess you could write something like

#define TWO (1+1)

to avoid precedence issues.

But why do I often see something like that:

#define TCS34725_ADDRESS (0x29)

Is there any point in having those parenthesis around a single value?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Piglet
  • 27,501
  • 3
  • 20
  • 43
  • 3
    The only point is consistency (and consistency is good -- except perhaps in this case). – pmg Oct 02 '20 at 08:26
  • 4
    BTW, I'd do `#define ADD(f1, f2) ((f1) + (f2))` – pmg Oct 02 '20 at 08:28
  • 1
    Does this answer your question? [Is there a good reason for always enclosing a define in parentheses in C?](https://stackoverflow.com/questions/9081479/is-there-a-good-reason-for-always-enclosing-a-define-in-parentheses-in-c) – phuclv Oct 02 '20 at 10:10

2 Answers2

3

Both 0x29 and (0x29) are primary expressions, so the only noticeable difference occurs when converted to string literals by macros:

#include <stdio.h>

#define A1 (0x29)
#define A2 0x29

#define MKSTR_(x) #x
#define MKSTR(x) MKSTR_(x)

int main(void)
{
    printf("%s\n%s\n", MKSTR(A1), MKSTR(A2));
    return 0;
}

Output:

(0x29)
0x29

If you only care about the numeric value, then parentheses around constants in the macro replacement text are superfluous and can be omitted.

Ian Abbott
  • 15,083
  • 19
  • 33
0

It depends where the macro is used. In some cases it makes sense

#define FOO1( f1, f2 ) ( f1 * f2 )
#define FOO1( f1, f2 ) ( (f1) * (f2) ) // recommended

give very different results when fed with

FOO1( 12+12, 13+12)

In the case of (0x29) it depends how it is used.

AndersK
  • 35,813
  • 6
  • 60
  • 86
  • 1
    You should point out that `#define FOO1( f1, f2 ) ( (f1) * (f2) )` is the only correct way – Jabberwocky Oct 02 '20 at 08:31
  • 1
    thanks. would you mind adding an example where it would make sense to have `(0x29)` instead of `0x29` because that's my question. "it depends" doesn't help me too much :) – Piglet Oct 02 '20 at 08:38