+ 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); }

4th Jun 2022, 5:55 AM
Rudra
Rudra - avatar
2 Answers
+ 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)
4th Jun 2022, 6:20 AM
Ipang
+ 1
Taking this one step further: always wrap your arguments in parentheses #define square(x) ((x)*(x)) Why? Imagine a call "square(x+y)" 😉
4th Jun 2022, 6:40 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar