0

I am using Visual Studio 2015 to learn some basic C. While experimenting with the EOF symbolic constant, I decided to lookup its definition and this is what I found:

#define EOF (-1)

I though it was kind of weird that the -1 was enclosed in parenthesis so I decided to create my own -1 symbolic constant so I did the following:

#define ABC -1

In the debugger, both EOF and ABC show as value -1 so I started wondering, why does the EOF definition uses (-1) to represent -1 when the parenthesis do not appear to be needed?

Thanks.

T555
  • 217
  • 2
  • 9
  • 9
    `int i = 0, j; j = i-ABC`. – too honest for this site Feb 10 '16 at 18:33
  • 4
    http://stackoverflow.com/questions/9081479/is-there-a-good-reason-for-always-enclosing-a-define-in-parentheses-in-c – Forhad Ahmed Feb 10 '16 at 18:35
  • 2
    @Olaf Very interesting, I would never think of it because `i-ABC` is impossible for me to write, I would write `i - ABC` so the problem wouldn't happen, but it's really nice that you gave this example as it clearly justifies the parentheses. – Iharob Al Asimi Feb 10 '16 at 18:35
  • @iharob: Yeah, I also would use spaces, of course. But just have a look at the code shown here ... – too honest for this site Feb 10 '16 at 18:36
  • @Olaf Interestingly gcc (Cygwin C Compiler 4.9.3 -std=c1x) compiled `#define ABC -1 int i = 0, j; j = i-ABC` just like `#define ABC (-1)`. Perhaps not all compilers are so behaved. – chux - Reinstate Monica Feb 10 '16 at 19:24
  • @chux: I did not intend to dig deeply in the standard for this question. AFAIK the more recent versions of the standard are more clear about how to match tokens (greedy, i.e. match the longest sequence). IIRC C99 added an artificial seperator between preprocessor tokens which changed the preprocessor semantics exactly for such cases, so the compiler will not join the `-`. However, older C variants definitively left that to the compiler. It was just a short example; maybe there are better ones with operator preceedence and or wrong syntax that will be caught by the parenthesis. – too honest for this site Feb 10 '16 at 19:43
  • @Olaf Agreed, Credit to [you](http://stackoverflow.com/a/35325235/2410359) – chux - Reinstate Monica Feb 10 '16 at 21:26

1 Answers1

4

It is always helpful, if not necessary, to add the necessary numbers of parentheses to a defined macro.

For example, if you do

#define SUM(a,b) a + b
#define MUL(a,b) a * b

int a = MUL(4+5, 2+3); // you get 4+5*2+3 = 17 instead of 45.
int b = 4 * SUM(1,1); // you get 4*1+1 = 5 instead of 8.

So you better write

#define SUM(a,b) ((a) + (b))
#define MUL(a,b) ((a) * (b))

And as it is a good habit, always use () in macros.

Another good reason is the example shown in the comments to your question.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 3
    I would say almost necessary not *always helpful*. It's weird but I have seen like 3 questions today related to this very issue – Iharob Al Asimi Feb 10 '16 at 18:37