+ 1

QUICK HELP with C

#define sqrt(i) i*i printf(“%d”, sqrt(3 +1)); Why is output 7?

12th Jul 2022, 11:21 PM
Boris Zugic
Boris Zugic - avatar
13 Réponses
+ 8
A C preprocessor macro is not like a function call, where the arguments are evaluated and the values get passed on the stack to the function. Quite differently, a macro defines a substitution of text in your source code that occurs before it gets compiled. If the macro is defined poorly like the example, the source code ends up looking like this before compiling: printf("%d", 3+1*3+1); See that i is literally "3+1", so i*i simply inserts '*' between two copies of i. Now when it compiles, the calculation reduces to 7. The right way to define a macro is to ensure the parameters are all surrounded by parentheses. As well, the whole macro expression is surrounded by parentheses so that the macro may be used in larger expressions. i.e., ((i)*(i)) Late edit: BroFar demonstrates it in this example: https://code.sololearn.com/ckKGtFEEOExn/?ref=app
13th Jul 2022, 12:08 AM
Brian
Brian - avatar
+ 2
Brian Thank you for the thorough explanation, makes more sense now!
13th Jul 2022, 12:22 AM
Boris Zugic
Boris Zugic - avatar
+ 2
Abhishek Mp Jacob Tracey already did so. i = 3+1 in that Case will save the entire Formular and so we will have 3+1*3+1 and when follow Mathmatical Rules that we have 7.
14th Jul 2022, 10:17 AM
Felix Alcor
Felix Alcor - avatar
+ 2
Yeahh i got it now, 3+(1*3)+1==7 thank you Jacob Tracey
14th Jul 2022, 10:22 AM
Abhishek Mp
Abhishek Mp - avatar
0
Jacob Tracey Thank you, but my intention was to understand why 7 exactly as this was a question given to me on a quiz. I remember from one of the lessons to always surround any calculations in a preprocessor with brackets.
12th Jul 2022, 11:39 PM
Boris Zugic
Boris Zugic - avatar
0
Jacob Tracey you can also just do printf("%d", sqrt((3+1)); And sadly I can not give you a good answer to that question.
12th Jul 2022, 11:44 PM
Felix Alcor
Felix Alcor - avatar
0
Jacob Tracey Ohhh, I see. Thank you!
13th Jul 2022, 12:04 AM
Boris Zugic
Boris Zugic - avatar
0
Can anyone explain how answer is 7 but not 16?
14th Jul 2022, 7:55 AM
Abhishek Mp
Abhishek Mp - avatar