+ 2
Why this code gives the output as 28? (Code mentioned below)
#include<stdio.h> #define square(x) x*x void main() { int i; i=(28/square(4)); printf("%d",i); }
2 Respostas
+ 2
Each presence of `square( <number> )` will be replaced with `<number> * <number>` before compilation phase begins. So ...
i = ( 28 / square( 4 ) );
Will be replaced into something like this
i = ( 28 / 4 * 4 );
If you want 28 to be divided by 16 (4 * 4), then wrap the macro arguments by parentheses inside the macro body as follows
#define square( x ) ( ( x ) * ( x ) )
This way, the line will be replaced into something like this
i = ( 28 / ( 4 * 4 ) );
(Edited)
+ 1
Taking this one step further: always wrap your arguments in parentheses
#define square(x) ((x)*(x))
Why? Imagine a call "square(x+y)" 😉