Why result is 8 but not 2? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why result is 8 but not 2?

#include<stdio.h> #define sq(x) x*x int main() {     int i = 8/sq(2);     printf("%d", i); }

6th Mar 2023, 9:34 AM
NIKHIL JOSHI
NIKHIL JOSHI - avatar
3 Answers
+ 6
Macro call is not a function call but a textual replacement before compilation. If you replace sq(2) in the expression, you get int i = 8/2*2 Since multiplication and division have the same precedence, it is evaluated left to right. That is, (8/2)*2, and that is 8.
6th Mar 2023, 10:23 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 5
Jay Matthews better yet, this would produce the expected results: #define sq(x) ((x)*(x))
6th Mar 2023, 9:46 PM
Brian
Brian - avatar
+ 1
It is because same precedence of * & / , and left to right evaluation.
7th Mar 2023, 8:06 AM
Sunil Choudhary
Sunil Choudhary - avatar