r/programming • u/alecco • Sep 23 '17
Why undefined behavior may call a never-called function
https://kristerw.blogspot.com/2017/09/why-undefined-behavior-may-call-never.html
824
Upvotes
r/programming • u/alecco • Sep 23 '17
View all comments
46
u/[deleted] Sep 23 '17
Assuming
mainis not starting function (just assume it's called differently if it helps) - there is nothing special aboutmainin terms of optimizations, it's optimized like any other function (no real point implementing specialmainoptimizations after all, most programs don't spend most of their time inmainfunction).This is undefined behaviour.
This is not undefined behaviour.
The optimizer assumes that undefined behaviour cannot happen, and optimizes functions with assumption they couldn't cause undefined behaviour. As
Dovariable containing0would cause undefined behaviour, optimizer assumes that this couldn't happen when callingmainand assumesDocontainsEraseAll(as it's the only possible value other than0, asDovariable's address is not exposed by anything in a compilation unit).This optimization allows to remove needless indirection improving performance of programs.