-2

I wrote a small piece of code in which I used #define with increment operator. The code is

#include <stdio.h>
#define square(a) ((a)*(a))

int main ()
{
    int num , res ;
    scanf ("%d",&num ) ;
    res = square ( num++ ) ;
    printf ( "The result is %d.\n", res ) ;
    return 0 ;
}

But while compiling this in gcc, I got the following note and warning:

defineTest.c:8:20: warning: multiple unsequenced modifications to 'num' [-Wunsequenced]
    res = square ( num++ ) ;
                      ^~
defineTest.c:2:21: note: expanded from macro 'square'
    #define square(a) ((a)*(a))
                        ^
1 warning generated.

Please explain the warning and note. The output I got was :

$ ./a.out
1
The result is 2.

$ ./a.out
2
The result is 6.

Also explain how the code works.

Community
  • 1
  • 1
BharathYes
  • 787
  • 2
  • 9
  • 25

1 Answers1

3

Your macro, after preprocessor expands it, will look like this:

((a++)*(a++))

Notice that, a++ is the same as a = a + 1, so you can rewrite expanded macro as:

((a = a + 1)*(a = a + 1))

You are changing value of a (or num, to be exact) twice in one statement, which generates warning, as this is undefined behaviour.

I would suggest you to rewrite your macro as a function

int square(int x)
{
    return x*x;
}
pmatyszok
  • 142
  • 5