Here is the code :
#include<stdio.h>
#define sqr(x) x*x
void main()
{
printf("\n%d",sqr(9));
printf("\n%d",sqr(5+4));
}
The output is : 81 29
Here is the code :
#include<stdio.h>
#define sqr(x) x*x
void main()
{
printf("\n%d",sqr(9));
printf("\n%d",sqr(5+4));
}
The output is : 81 29
Having SQR as a macro will never be correct. Make it a function. In C++, the function can be constexpr
, in C it should probably be inline
.
The following code goes through all iterations of attempting to fix the macro. Note how only the function gives the correct result and no macro does.
#include <stdio.h>
// Original (very incorrect)
#define SQR(x) x*x
// First correction (still incorrect)
#define SQR2(x) (x)*(x)
// second correction (still incorrect)
#define SQR3(x) ((x)*(x))
// correct
int square(int x){ return x*x; }
int main()
{
int x1 = SQR(5);
printf("5²=%d (correct so far)\n", x1);
int x2 = SQR(1+1);
printf("(1+1)²=%d (problem: operator precedence)\n", x2);
int x3 = SQR2(1+1);
printf("(1+1)²= %d (first correction)\n",x3);
printf("sizeof (int) = %d\n", sizeof(int));
int x4 = sizeof SQR2(1+1);
printf("sizeof (1+1)²= %d (problem: operator precedence)\n", x4);
int x5 = sizeof SQR3(1+1);
printf("sizeof (1+1)²=%d (second correction)\n", x5);
int i=2;
int x6 = SQR3(i++);
printf("(i++)²=%d (expected: 4, problem: undefined behavior)\n", x6);
i=2;
int x7 = SQR3(++i);
printf("(++i)²=%d (expected: 9, problem: undefined behavior)\n", x7);
i=2;
int x8 = square(i++);
printf("(i++)²=%d (expected: 4)\n",x8);
i=2;
int x9 = square(++i);
printf("(++i)²=%d (expected: 9)\n",x9);
}