-3

I am trying to do following:

char c[] = "programming";
char *p;

*(c-1)='l';
*(c-2)='l';
*(c-3)='l';
*(c-4)='l';
*(c-5)='l';
p=&c[0];

cout<<*(c-1); 

This prints l only if I omit p=&c[0]; why is that so? There is no relation apparently between p and c.

1 Answers1

6

Your expectation that there should be a relation is fundamentally flawed.

This is all undefined. There are so many optimisations that the compiler is allowed to do, and other ways in which is may wield the flexibility offered unto it by the language, that you can not make any assumptions with this stuff.

Just don't attempt it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • How undefined? A little reasoning will help. – user3541689 Apr 16 '14 at 15:42
  • @user3541689, `c-1` results in a pointer not within the array, thus UB. Past that, you then dereference said pointer and assign to it. – chris Apr 16 '14 at 15:43
  • 3
    @user3541689: There aren't levels of undefinedness. You can't have something that is like 40% undefined, and another thing that is only 30% undefined. This is not defined by the language, full stop. The best you could do would be to examine your compiler's documentation and source code, then only ever use that build of that particular version of that specific make of compiler, on that one computer with the exact same command-line arguments. Sound like fun? – Lightness Races in Orbit Apr 16 '14 at 15:43
  • Oh, and never modify your source code either. Optimizers make different decisions based on heuristics, so... – Puppy Apr 16 '14 at 15:47
  • p is probably underneath C on the stack, so writing to p wipes the l out. Nevertheless, UB for sure. – Martin James Apr 16 '14 at 15:47
  • This discussion is not even worth having. It's UB - I am actually surprised no nasal demons have appeared. – ScarletAmaranth Apr 16 '14 at 15:48
  • @ScarletAmaranth: They have, but this is _so_ UB (levels!) that the demons appeared under someone else's nose. Consequently, it may take a while for the OP to become aware of them. – Lightness Races in Orbit Apr 16 '14 at 15:54