Question

I have a simple program to calculate the volume of a cube. It runs fine, but the result I get is wrong. It comes out as "Y is 392". Can anyone help me understand why it is 392? I have just begun C, so I do not understand all of the code.

I realise this Macro is badly written, I am just trying to understand its behavior before I rewrite it.

#define CUBE(x) (x*x*x)

void main(void);

void main(void){
    int x, y;
    x = 5; 
    y = CUBE(++x);
    printf("Y is %d \n", y);
}
Was it helpful?

Solution

This is because the macro expands to:

y = ++x * ++x * ++x;

This is a very badly written macro, for this very reason; it looks like a function call (which would evaluate the argument only once) but it really evaluates it three times.

This gives undefined behavior since there is a lack of sequence points.

OTHER TIPS

The reason this happens is that the macro pre-processor substitutes the parameters as they are. So, CUBE(++x) is expanded to:

++x*++x*++x

You should avoid using expressions with side effects in macros because of this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top