0

I'm trying to figure out what is the issue with the following code. I have the idea, based on various internet search, that it causes undefined behavior but i'd like to have better understanding.

#include <iostream>
#define SQUARE (x) x*x

int main()
{
int l=5;
std::cout<<"test"<<SQUARE(l++)<<std::endl;
std::cout<<l<<endl; //check
std::cout<<"test1"<<SQUARE(++l)<<std::endl;
}

I have compiled and run the program with Dev X++ 5.11 (so cpp) and i have obtained the following output:

test 30

7

test1 81

consequently i have understood that in test the compiler start executing the multiplication (l=5) then adds 1 (l=6) then identifies the second element of the multiplication (l=6 --> result 30) and concludes adding 1 (l=7 as shown by the check). As far as test1 the compiler adds 1 to the first element of the multiplication (l=8), then adds again 1 (l=9) and in the end it multiplies (9*9=81).

QUESTION: is this behavior consistent or does it depend on the specific compiler?

Thanks to everyone in advance

  • 1
    It is indeed undefined behavior due to lack of [sequence points](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) so whatever output you see is not guaranteed. – Cory Kramer Apr 11 '17 at 14:18
  • 1
    The preprocessor turns `SQUARE(l++)` into `l++*l++` which is undefined behavior as discussed [here](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). – nwp Apr 11 '17 at 14:20

0 Answers0