Hacker News new | past | comments | ask | show | jobs | submit login

Fascinating. Does anyone know why x escapes here? Is it an optimization miss? Because to my untrained eye modifying x should still be undefined behavior.

Does the way x is initialized make it not "const-y" enough?




I tried gcc, clang, msvc, and icc. They all generated the load and either an add or an inc. https://godbolt.org/z/han78n9zM If we define `f` to const_cast away the const and add 10: https://godbolt.org/z/1dso8ojWG all the compilers agree that we should get 53. However, make `y` const, so we have

  const int y = 42;
  const int x = y;
and now modifying x suddenly becomes undefined behavior, and x + 1 returns 43 https://godbolt.org/z/cqbGasrMM Similar to how the original assembly showed making `y` const removed the reload and increment/+1 of x.

So, it seems that all these compilers agree that modifying `x` is undefined behavior if `y` is const, but is defined if `y` is mutable.

I am not sure why this is.

I may have misunderstood, but I didn't get the impression this should be the case from reading: https://en.cppreference.com/w/cpp/language/cv

My best guess is that for some reason, `x` is a constant object only if initialized itself via a constant object. But I couldn't find anything saying that is the case. I asked on the #learn channel of cppslack.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: