-3
#include<stdio.h>
#define SQ(x) ((x)*(x))

main()
{
    int i = 1;
    while( i<=5 ){
        printf("result : %d\n", SQ(i++));
    }
}

execute window :

result : 2 result : 12 result : 30

I intended that:

result : 1 result : 4 result : 9 result : 16 result : 25

How should I modify this code?

Krish Munot
  • 1,093
  • 2
  • 18
  • 29
이동준
  • 25
  • 1
  • 5

2 Answers2

1

SQ(i++) -> (i++)*(i++)

Use this:

printf("result : %d\n", SQ(i));
i++;
Kirill Bulygin
  • 3,658
  • 1
  • 17
  • 23
0

A macro may evaluate its argument more than once. This is because #define textually substitutes, with no regard for C language rules. The preprocessor replaces SQ(i++) with

((i++)*(i++))

In this expression, i++ is done twice, and not once.

This is why the use of #define is not recommended. Write a regular function instead, for the behavior you desire. Or, call SQ with an argument of i, and only after the call, write i++:

SQ(i);
i++;
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75