why answer is7? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

why answer is7?

What is output of this code? #define sqr(x) x*x int main() { printf(”٪d”, sqr(3+1);}

8th Aug 2019, 7:26 AM
Nika Soltani Tehrani
Nika Soltani Tehrani - avatar
4 Answers
+ 17
#define sqr(x) x*x // sqr(3+1) = 3 + 1*3 + 1 = 7 #define sqr(x) (x)*(x) // sqr(3+1) = (3+1)*(3+1) = 16 #define sqr(x) (x*x) // what is the output... ?
8th Aug 2019, 8:27 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 8
As you define sqr(x) x*x mean which you passing argument that will be multiplied two times Now sqr(3+1) define it will treat like 3+1*3+1 As multiplication has higher precession that why it will be 3+3+1=7 That is my point of view.. Nika Soltani Tehrani
8th Aug 2019, 7:39 AM
Scooby
Scooby - avatar
+ 4
sqr(3+1) will be interpreted as - 3+1*3+1 = 3+3+1 = 7, as * has higher precedence. To get ur expected result correct the macro - #define sqr(x) ((x)*(x)) Observe additional '()' around macro expansion. Hope this helps...!!!
8th Aug 2019, 7:42 AM
Kuri
Kuri - avatar
+ 4
Thanks a lot guys🙏🙏🙏
8th Aug 2019, 10:32 AM
Nika Soltani Tehrani
Nika Soltani Tehrani - avatar