0

I have noticed this strange behavior of macro functions while using pre increment operator. I know it is not preferable to use pre increment operator with macros but still I would like to know the reason behind the execution of the following 2 codes:

#include <stdio.h>

#define SQR(x) {x*x }

int main()
{
    int a=4;
    int b=SQR(a++);
    int c=SQR(++a);
    printf("%d.....%d....%d\n",b,c,a*b*c); 
    return 0;
}

The output of this is:

20.....64....10240

The first value b is 20, which is okay 4*5. But why the value of C is 64 i.e. 8*8 instead of 7*8?

And I just replaced the sequence of execution like this:

#include <stdio.h>

#define SQR(x) {x*x }

int main()
{
    int a=4;
    int c=SQR(++a);
    int b=SQR(a++);
    printf("%d.....%d....%d\n",b,c,a*b*c); 
    return 0;
}

The output of this is:

42.....36....12096

Strange isn't it? The pre increment again had some issue. It gave 42 i.e. 6*7 instead of 5*6 and after that the post increment also gave wrong answer 36 i.e. 6*6 instead of 6*7.

It would be a great help if anyone can explain why the outputs are like this?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • undefined behavior – Danh Dec 14 '16 at 17:32
  • It's not quite a duplicate of http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior as OP might be confused about what macros do (as assumed by Sourav Ghosh's answer). – Ian Abbott Dec 14 '16 at 18:06
  • hey @Danh actually this question was asked in one of my exams, hence I thought there should be someway to get the answer. – user7297996 Dec 14 '16 at 18:06
  • Another useful and relevant Q&A is http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – Cody Gray - on strike Dec 14 '16 at 18:39

1 Answers1

2

MACROs are textual replacement, so your code

 SQR(a++)

expands to something like

 a++ * a++

and, int c=SQR(++a); to int c = ++a*++a;

which invokes undefined behavior. To elaborate the why part for this, please refer to this well-written answer.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Ain't there any way to get the answer atleast for the first function, coz that is what I got in one of my exams – user7297996 Dec 14 '16 at 18:07
  • 1
    @user7297996 nopes, UB is...UB. that's it. – Sourav Ghosh Dec 14 '16 at 18:08
  • Okay thank you for ur help – user7297996 Dec 14 '16 at 18:08
  • 2
    If this is a question on an exam, either your teacher is tricking you and the answer is "undefined behavior", or your teacher has no idea what they're doing and has no business teaching C. (An alternative answer that I would have accepted would be, "I have no idea, but if you ever wrote code like this, you deserve to have your butt kicked, so it doesn't really matter.") – Cody Gray - on strike Dec 14 '16 at 18:39