r/programmingmemes 17d ago

compilers be like

Post image
144 Upvotes

20 comments sorted by

View all comments

Show parent comments

3

u/scalareye 16d ago

They do, the dev can implement whatever they want the compiler to do with that code

0

u/HyperWinX C++ 16d ago

They can. And they implement whatever standard says to implement. Everything that is not defined by the standard is undefined behavior.

1

u/scalareye 16d ago

Right but my point is if you know what the compiler will do you can use UB. It might do different things for different optimizations but with flags you can tell it what you want it to do.

1

u/luciferoussky72 16d ago

Well, lots of “undefined behavior” that ends up working in practice can still cause subtle bugs. Take C-style type punning. Where you type “long y = * (long*) &x;” when x is a double. Technically, it works, but the compiler is actually allowed to assume that pointers of different types* can’t point to the same memory address, so type punning can cause subtle bugs if you use it in the wrong place. Plus, there are better alternatives like memcpy, C++ reinterpret_cast, etc.

*with the exception of char* and void*, which can “alias” (the technical term for pointer overlap rules) any other type