0

I am new to C language, and I meet the problem with the printf. Here is the code:

#include <stdio.h>

#define add1(x) ((x) = ((x)+1))


int main()
{
    int x, y, temp;
    x = 5;
    
    printf("Add 1 to %d is equal to: %d", x, add1(x));
    
    return 0;
}

After compiling and running this code, it shows the result:

Add 1 to 6 is equal to 6

What I expect is: "Add 1 to 5 is equal to 6"

That is, what I expect is that the behavior of it will show the format specifier by order: "Add 1 to x" (x = 5), and then "is equal to: add1(x)" (x = x+1 --> x=6) However, it seems that the compiler will compile add(x) simultaneously and directly make x = 6 while running to the line "printf("Add 1 to %d is equal to: %d", x, add1(x));"

Can someone help explain this problem with more detail? Thanks~

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 1
    Undefined behaviour — anything is a valid result. – Jonathan Leffler Jun 19 '23 at 04:15
  • This code in this question used marginally different syntax from the pre-increment and post-increment notations, but the net result is the same — undefined behaviour because there is no sequence point between the different argument expressions being evaluated and there is no defined order in which function arguments are evaluated. – Jonathan Leffler Jun 19 '23 at 04:20
  • Thanks for providing the information about "Undefined behavior". I have looked for some articles introduce this topic, and those help me realize this issue more. – Allen0505 Jun 19 '23 at 08:33
  • The `add1` macro is a bad idea. Just write `x++` like the rest of the world. Hiding it in a macro, and even worse, writing that macro to unexpectedly evaluate its argument more than once, is a bad idea. – Tom Karzes Jun 19 '23 at 12:38

0 Answers0