Day#114 C coding challenge | Why the output of this code is not 121?

Day#114 C coding challenge | Why the output of this code is not 121?


Explanation:
We might have expected, 121 as output but the output is different. Let us know the reason.
In the above code, the preprocessor replaces Sqrt(x) with x * x literally in the code without checking for correctness or operator precedence. so,

number_2 = 10+1*10+1 = 10+10+1 = 21

Because of operator precedence * gets executed before +

About preprocessor directive:
When preprocessor directive is used, it is processed at code compile time during the pre-processing stage, before the compiler sees any C code. It is expanded inline and reduces any function overhead

To get 121, in the above code, rewire the preprocessor directive as,
#define Sqrt(value) ((value)*(value))

Post a Comment

0 Comments