1

Why the output of the below program is 125 and not 5?

#include<stdio.h> #define square(x) x*x int main() { int var; var = 125/square(5); printf("%d",var); return 0; } 
1
  • The answers give are correct but maybe you would want to understand that macros is C are only text substitutions not actual code (they are writing new code for you). Macros run before the compiler tries to compile your code and are part of what is called the pre-processor. As pointed out, avoid them for math or function things and use lots of parenthesis when in doubt. Commented May 14, 2020 at 0:56

2 Answers 2

3

This line:

var = 125/square(5); 

is expanded into:

var = 125/5*5; 

which evaluates from left to right to 25*5 and then to 125;

To fix it, parenthesize the argument in the definition of square, like this:

#define square(x) ((x)*(x)) 

Note also the extra parenthesis around x in order to achieve expected behavior when e.g. 1+2 is passed into square.

Sign up to request clarification or add additional context in comments.

Comments

2

Note that var = 125/square(5); becomes var = 125/5*5 when you compile the code.
So the compiler calculates 125/5 before 5*5. The result becomes (125/5)*5 = 125.

Instead of #define square(x) x*x, put #define square(x) (x*x).

Here is your code:

#include<stdio.h> #define square(x) (x*x) int main() { int var; var = 125/square(5); printf("%d",var); return 0; } 

1 Comment

which is why you dont put functions in defines if you can help it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.