0

The following code is designed to specifically return the value 36 instead it returns 49 but can't see how or why. Any help would be appreciated.

#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>

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

static int Func1(void)
{
    static int n = 1;

    // Returns 4
    return n*++n;
}

int main()
{
    static int Incs = Func1();

    printf("%d\n", MUL(ADD(1, Incs), MUL(3, 4)));
}
Nexuz
  • 192
  • 12

2 Answers2

5

I suggest you check the preprocessed output, because it will not be what you expect it to be.

To be more precise:

  • ADD(1, Incs) expands to 1+Incs
  • MUL3, 4) expands to 3*4
  • MUL(1+Incs, 3*4) expands to 1+Incs*3*4

That's why it's recommended to always use parenthesis around the arguments in a macro, like

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

Even worse is what is pointed out by Niall in a comment, because the expression n*++n leads to undefined behavior. Undefined behavior makes your whole program ill-formed, and will make any output suspect.

You should really read the accepted answer in the link provided by Niall.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Lets break it:

MUL(ADD(1, Incs), MUL(3, 4))

As Incs = 4, it can be written as:

MUL(ADD(1, 4), MUL(3, 4))

MUL(1+4, 3*4)

1 + 4 * 3 * 4

Now compiler does some BODMAS

1 + (4*3*4)

1 + 48

49

Hence proved.

Oh But you don't want this behavior, and want each macro to work seperately then change your macro definitions a bit

#define MUL(a,b) (a)*(b)
#define ADD(a,b) (a)+(b)
foobar
  • 2,887
  • 2
  • 30
  • 55