1

I am trying to comprehend the output of my code over here:

#include <stdio.h>
#define DOUBLE(x) (x+x)

int main() {
    int i, j;
    i = j = 3;

    printf("%d\n", DOUBLE(++i));  // Output: 10
    printf("%d\n", DOUBLE(j++));  // Output: 7

    return 0;
}

This is my interpreatation: DOUBLE here is a macro, hence the pre-processor replaces

  • DOUBLE(++i) to (++i + ++i) and,
  • DOUBLE(j++) to (j++ + j++)

The compiler then pre-increments i and post-increments j before the addition operation in each statement.

  • (5 + 4)
  • (3 + 4)

My logic (fails) does not match the output. What is happening behind the scenes when I call DOUBLE with argumnets having increment operators.

Adarsh TS
  • 193
  • 15
  • 3
    You understand the preprocessor correctly, but your understanding of the expressions `++i + ++i` and `j++ + j++` is incorrect (see linked question) – M.M Oct 30 '20 at 02:26
  • 5
    Yes, `DOUBLE(++i)` expands to `(++i + ++i)` which is [undefined behavior](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior/949508#949508). `DOUBLE(j++)` is undefined behavior also. – Nate Eldredge Oct 30 '20 at 02:27

0 Answers0