-4

My professor gave me this code and told me that it has "Undefined Behaviour":

#include <iostream>

int main()
{

    const int WEEKDAYS = 7;
    const int *pWeekdays = &WEEKDAYS;
    *((int*)pWeekdays) = 9;
    std::cout << WEEKDAYS;
    std::cout << *pWeekdays;

    return(0);
}

It gives the following output:

79

I am trying to understand the following:

  1. Why is the behaviour undefined?
  2. Why does printing *pWeekdays output 9 but printing WEEKDAYS outputs 7?
dinomoth
  • 86
  • 6
  • 4
    You have undefined behaviour. You cannot expect this code to do anything reliable. – juanchopanza Jul 10 '14 at 14:59
  • Modifying [a const is undefined behavior](http://stackoverflow.com/a/22656791/1708801), most likely since it is a const the compiler is replacing it with a literal and not even evaluating the variable. – Shafik Yaghmour Jul 10 '14 at 15:00
  • @juanchopanza my professor called it that way... but I do not understand the behavior of these two variables. – dinomoth Jul 10 '14 at 15:01
  • It is an interesting question, although it is a duplicate, SO frowns on posting code as images. – Shafik Yaghmour Jul 10 '14 at 15:02
  • The only thing to understand is that the program can do whatever it wants. You can look at the assembly code generated by this code on your particular platform to see exactly what is going on. – juanchopanza Jul 10 '14 at 15:03
  • @Shafik Yaghmour I edited the question as you suggested. Thanks – dinomoth Jul 10 '14 at 15:14
  • @ShafikYaghmour I've added some further improvements. I also agree that the question no longer deserves downvotes. The only thing wrong with it now is that it is a duplicate, but its already been closed for that reason. – JBentley Jul 10 '14 at 15:17
  • @Shafik Yaghmour Thank you for your patience with my stumbling... I am learning the hard way, and accepting any condemns from this wonderful community – dinomoth Jul 10 '14 at 15:23

1 Answers1

3

You have undefined behaviour because you are modifying a object that was declared const. You are not allowed to do this.

The reason that this is undefined behaviour is to allow the compiler to perform optimisations, which it appears to be doing in this case. It has replaced all instances of WEEKDAYS with the value 7, so the first cout line becomes this:

std::cout << 7;

That's why it prints 7 regardless of what you do to the object that pWeekdays points at.

This behaviour is still undefined though. There's no reason it has to do this at all.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324