Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

some error in output in using macro in C

Tags:

c

my code is:-

#include<stdio.h>
#include<conio.h>

#define sq(x) x*x*x

  void main()
  {
    printf("Cube is : %d.",sq(6+5));
    getch();
  }

The output is:-

Cube is : 71.

now please help me out that why the output is 71 and not 1331...

thank you in advance.

like image 778
Himanshu Aggarwal Avatar asked Nov 30 '25 05:11

Himanshu Aggarwal


2 Answers

Always shield your macro arguments with parenthesis:

#define sq(x) ((x) * (x) * (x))

Consider the evaluation without the parenthesis:

6 + 5 * 6 + 5 * 6 + 5

And recall that * has a higher precedence than +, so this is:

6 + 30 + 30 + 5 = 71;

Get to know the precedence rules if you don't already: http://en.cppreference.com/w/cpp/language/operator_precedence

like image 83
pb2q Avatar answered Dec 02 '25 21:12

pb2q


You need parentheses around the argument.

#define sq(x) ((x)*(x)*(x))

Without the parentheses, the expression will expand to:

6+5*6+5*6+5

Which you can see why it would evaluate to 71.

A safer solution would be to use an inline function instead. But, you would need to define a different one for each type. It might also be more clear to rename the macro.

static inline int cube_int (int x) { return x*x*x; }
like image 35
jxh Avatar answered Dec 02 '25 22:12

jxh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!