2784 views
2

I am not able to understand this code

``````#define sqt(x) x*x
int main(){
print("%d",sqt(3+1));
}
``````

Manually I am getting the output of 10 But when write the code and compile it I am getting the answer as 7 so please explain me this

How did you get 10?

7 is the correct answer. If the want the answer to be 16, add some parentheses. I have no idea how to get to 10.

@kingW3 Maybe he meant `0x10`? :)

@LeeDanielCrocker Or maybe he thinks it will expand to `3*3+1` for some reason.

4

Remember, since you're using a macro, `3 + 1` is not evaluated before `sqt` is called. `x` becomes `3 + 1` (not `4`), then order of operation causes an unexpected answer to be produced since addition happens after multiplication. This means that:

``````sqt(3 + 1)
``````

expands to:

``````3 + 1 * 3 + 1 // Multiplication happens first
3 + 3 + 1
7
``````

This is a good example of why you shouldn't use macros unless they're strictly necessary, or you've made proper care to ensure that things like this can't happen. As @Barmar points out this particular case can be remedied by having the macro expand to include parenthesis:

``````#define sqt(x) ((x)*(x))
``````

Which would cause the evaluation to differ and give a proper answer:

``````(3 + 1) * (3 + 1)
4 * 4
16
``````

posted this