2
#include<stdio.h>
#include<conio.h>
#define square(v) v*v
void main()
{
int p=3;
int s=square(++p);
printf("%d %d",s,p);
getch();
}

output 25 5 Why 16 4 is not coming as output? (Advance thanks)

rohan lukose
  • 101
  • 1
  • 13
  • See for example http://stackoverflow.com/questions/3605005/evaluate-macro-parameter-once-only for a workaround. – Cascabel Oct 07 '11 at 15:54

2 Answers2

12

A macro is basically a text copy and paste. Therefore your ++ is being duplicated.

The macro is being expanded as:

s = ++p * ++p;

That's the danger of macros. (in this case, it also invokes undefined behavior)

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • 1
    Out of curiosity, what is undefined about this? – MGZero Oct 07 '11 at 15:56
  • 2
    There's two `++` in the same statement on the same variable. That's undefined. – Mysticial Oct 07 '11 at 15:57
  • 5
    @MGZero The expression has no [sequence points](https://secure.wikimedia.org/wikipedia/en/wiki/Sequence_point), so there's no predicting when the pre-increment operations will take effect. – Praetorian Oct 07 '11 at 15:57
3

the behavior of

++p * ++p

is undefined, it depends on the compiler

You may use inline instead

inline int square(int p) {
    return p * p;
}
lostyzd
  • 4,515
  • 3
  • 19
  • 33