The questions may be like this: Why does this code = 27 instead of 7³ = 343. The way code is treated has to do with the C preprocessor .

#include <stdio.h>

#define x 5+2  /* Focus here*/

int main(void)
    int i;
    return 0;

In order to understand why this code provides not the result the programmer expected, we should remember how define works. The define comes in this form:

#define token [value]

So, every time the compiler sees in the code the token, it will go and replace the token with what is into the brackets, thus the value. I think that is simple to understand.

Now, let’s perform the rule above, in the code given. We have #define x 5+2. As a result, token is x and value is 5+2. The operation we want to perform is this: i=x*x*x; . So, we should act like the compiler, in order to really understand why we get a logical error there. Replace x with the value, that is putting wherever we see an x, the 5+2.
So, we have i = 5+2 * 5+2 * 5+2 . But since, multiplication has higher precedence than the addition, thus * is going to operate before the + sign, we have i = 5 + 10 + 10 + 2 => i = 15 + 10 + 2 => i = 25 + 2 => i = 27.

How we get around this? We simple enclose our value in parenthesis! We should write #define x (5+2) and that should do the trick. Now we have i = (5+2) * (5+2) * (5+2) = 7 * 7 * 7 = 49 * 7 = 343. That is what we wanted.

But since this holds true:
let’s see another example.

#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main(void)
    int i = 3;
    int j = 4;
    int m;
    m = MAX(i++, j++);
    printf("max = %d, i = %d, j = %d\n", m, i ,j);
    return 0;

which outputs max = 5, i = 4, j = 6. As you can see j got increased by two! Why? Because b got executed twice 😉

More variation – where will it stop?
The functions are back to being called in what seems to be precedence order.
But wait, R1=R2=20
Everything else up to now has been R1=R2=16

Bravo to Salem! And all the other guys that contributed to this. 🙂

Have questions about this code? Comments? Did you find a bug? Let me know! 😀
Page created by G. (George) Samaras (DIT)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s