Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this undefined behaviour and why?

Tags:

c++

Please, explain why this code is correct or why not: In my opinion, line ++*p1 = *p2++ has undefined behaviour, because p1 is dereferenced first and then incrementing.

int main()
{
   char a[] = "Hello";
   char b[] = "World";

   char* p1 = a;
   char* p2 = b;

   //*++p1 = *p2++; // is this OK?
   ++*p1 = *p2++; // is this OK? Or this is UB?

   std::cout << a << "\n" << b;

   return 0;
}
like image 543
innochenti Avatar asked Mar 03 '26 13:03

innochenti


1 Answers

The first is ok

*++p1 = *p2++ // p1++; *p1 = *p2; p2++;

the second is UB with C++ because you are modifying what is pointed by p1 twice (once because of increment and once because of assignment) and there are no sequence points separating the two side effects.

With C++0x rules things are different and more complex to explain and to understand. If you write intentionally expressions like the second one, if it's not for a code golf competition and if you are working for me then consider yourself fired (even if that is legal in C++0x).

I don't know if it is legal in C++0x and I don't want to know. I've too few neurons to waste them this way.

like image 67
6502 Avatar answered Mar 06 '26 02:03

6502