0

Can someone explain me how we get these outputs? especially the third output (6), thanks.

#define A(x) ((x)+(x))
#define B(x) (2*(x))

int main()
{
    int a = 1;
    printf("%d\n", A(a++)); // print 3
    a=1;
    printf("%d\n", B(a++)); // print 2

    a=1;
    printf("%d\n", A(++a)); // print 6
    a=1;
    printf("%d\n", B(++a)); // print 4

    return 0;
}
Shir Cohen
  • 41
  • 1
  • 1
  • 4
  • When you expand the `A(a++)` or `A(++a)` macro you can easily see, that it's UB (as stated in many other QAs) – Ctx Mar 13 '20 at 14:53
  • See also [Why are preprocessor macros evil?](https://stackoverflow.com/q/14041453/10077) – Fred Larson Mar 13 '20 at 14:54
  • 1
    Unpack the macro manually: `A(++a)` will become: `(++a + ++a)`. Now, which of the two `++a`s will be executed first? – ForceBru Mar 13 '20 at 14:54
  • @ForceBru Actually, as the OP has no space in the macro definition, `A(++a)` becomes `++a+++a` - which could be seen (in fact *is* seen by MSVC) as `++a++ + a`. (gives "error C2105: '++' needs l-value") – Adrian Mole Mar 13 '20 at 15:01
  • @AdrianMole - No it can't in a conforming implementation. The preprocessor is meant to deal with **tokens**. Even without the space, that is still `+ ++` – StoryTeller - Unslander Monica Mar 13 '20 at 15:07
  • @StoryTeller MSVC isn't conforming. – Weather Vane Mar 13 '20 at 15:09
  • @WeatherVane - I'm well aware. There's plenty of evidence to that. – StoryTeller - Unslander Monica Mar 13 '20 at 15:09
  • Pease read the proposed duplicate (see link above) and rephrase this question to not involve the undefined behaviour of `++a + ++a`. Otherwise this whole questions is dominated by that UB, becoming a duplicate. Rephrase it with other experiments on your macros and it could be answered. – Yunnosch Mar 13 '20 at 15:12
  • @ShirCohen always parenthesise in macros `#define A(x) ((x)+(x))` although that won't help much in this case. – Weather Vane Mar 13 '20 at 15:12

0 Answers0