Why result is 8 but not 2? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
+ 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