What Happens When We Lie to the Compiler?
Posted on November 13th, 2009 at 12:57 by fr3@K

When you lie to your compiler, don’t be surprised to get results those differ from what you expect.

In this case, the coder promised his/her compiler the value of “value” won’t be changed, as it was declared const.

Therefore our best friend (yes, the compiler) who trusted the coder, thought “hey, I could cache this value in a register and not fetch it from RAM every time I reference it”, i.e. optimization.

If we change the code in the link slightly, so that function funcC would print *value before the assignment, one would see that the value of *value had actually been modified by function funcA. However, the modification was not visible in main, because the compiler was lied to as the coder explicitly told it that there would be no modification to value.

In the body of function funcC, though value was declared as a pointer to const instance, the compiler was smart enough to know it was lied to. There was a const_cast and a assignment, therefore, the modification to *value was reflected in the output.

del.icio.us:What Happens When We Lie to the Compiler? digg:What Happens When We Lie to the Compiler? spurl:What Happens When We Lie to the Compiler? newsvine:What Happens When We Lie to the Compiler? furl:What Happens When We Lie to the Compiler? Y!:What Happens When We Lie to the Compiler? 黑米共享書籤:What Happens When We Lie to the Compiler? 推推王:What Happens When We Lie to the Compiler?
Previous Post
« Texas Army Base Rampage «
Next Post
» 一看就知道 – 不 Thread-Safe 的 API »

Zero Comments »

No comments yet.

Comments RSS TrackBack URI

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>