+ 1
QUICK HELP with C
#define sqrt(i) i*i printf(“%d”, sqrt(3 +1)); Why is output 7?
13 odpowiedzi
+ 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
+ 2
Brian Thank you for the thorough explanation, makes more sense now!
+ 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.
+ 2
Yeahh i got it now, 3+(1*3)+1==7 thank you Jacob Tracey
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.
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.
0
Jacob Tracey Ohhh, I see. Thank you!
0
Can anyone explain how answer is 7 but not 16?