-8
#include<stdio.h>
#define prod(a,b) ((a>b)?a*a:b*b)

int prod1(int a,int b){
       return ((a>b)?a*a:b*b);
}

int main(){
        int p=0,q=-1;
        int p1=0,q1=-1;
        printf("%d ",prod(p1++,q1++));
        printf("%d ",prod1(p++,q++));
        return 0;
}

Output is: 1 0

Why is it different? How is the macros definition different from the function definition and why does it produces different results? Shouldn't all 2 outputs be equal to 0?

Abhinav Singi
  • 3,379
  • 1
  • 20
  • 27

3 Answers3

3

In the macro

#define prod(a,b) ((a>b)?a*a:b*b)

a and b are referenced more than once. So

prod(p1++,q1++)

becomes

(p1++ > q1++) ? p1++*p1++ : q1++*q2++

Note that this is very different than calling the function

prod1(p1++, q1++)

which only increments p1 and q1 once. And does so predictably.

Charlie Burns
  • 6,994
  • 20
  • 29
0

The macro's arguments a and b are copied as text into the expanded body of the macro, so prod(p1++,q1++) expands to ((p1++>q1++)?p1++*p1++:q1++*q1++) which is obviously different to what the function evaluates.

In standard C it is undefined if a single object is modified more than once between successive sequence points, so the macro causes undefined behaviour.

markgz
  • 6,054
  • 1
  • 19
  • 41
0

Look for the code that is compiled after the pre-processor has finished its jobs:

int prod1(int a,int b){
       return ((a>b)?a*a:b*b);
}

int main(){
    int p=0,q=-1;
    int p1=0,q1=-1;
    int p2=0,q2=-1;
    printf("%d ",((p1++>q1++)?p1++*p1++:q1++*q1++));
    printf("%d ",prod1(p++,q++));
    printf("%d ",(p2>q2)?p2*p2:q2*q2);
    return 0;
}
Amadeus
  • 10,199
  • 3
  • 25
  • 31