-4

I was working with c puzzles, and came across this question . In here , a at printf statement the pointer gets incremented once, so i thought it will be pointing to the random number ! but I cant understand why 25 is the output? could anyone please help me understand ? Many thanks in advance;)

void main()

{

      int  const * p=5;

      printf("%d",++(*p));

}

Answer: 25

Nisha
  • 1,783
  • 4
  • 18
  • 34

3 Answers3

6

You are pointing at a random piece of memory (address 5). You're then incrementing whatever happens to be stored there, and printing the result. This is undefined behaviour; your program could do anything.

UPDATE: Actually, this code shouldn't even compile. You've declared it as a pointer to const, so the compiler shouldn't let you increment. What compiler are you using?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • I think it`s a const pointer, so incrementing value at the target should be ok. – Gunther Piez Feb 23 '12 at 08:55
  • it's `int const *`, not `const int *`: `++p` would be illegal, not `++*p` – CAFxX Feb 23 '12 at 08:56
  • 2
    @CAFxX: `int const *` and `const int *` are the same thing. – Oliver Charlesworth Feb 23 '12 at 09:03
  • @drhirsch: That would be `int *const p`. – Oliver Charlesworth Feb 23 '12 at 09:04
  • `int const * == const int *`... what you mean is `int * const`, `const` can go on any side but to avoid confusion it should always be put right of the type and constness read from right to left. – Bort Feb 23 '12 at 09:08
  • @Bort: To avoid confusion? I think the above comments prove otherwise. http://stackoverflow.com/questions/3694630/c-const-reference-before-vs-after-type-specifier/3695979#3695979 – jamesdlin Feb 23 '12 at 10:46
  • @jamesdlin well, my opinion: that's why left `const type` should always be warned by the compiler! I know a lot of people write code otherwise but that's the source of the confusion if `const` is used in advanced types like here (and precedence rules apply). I learned it the hard way exactly because of this (imho) bad style. – Bort Feb 23 '12 at 11:36
1

What you are trying to do is wrong. Its making a pointer from an integer without a cast.Also your declaration makes p a pointer to an constant integer and you cannot increment the value pointed to by pointer p. Also its the value and not the pointer that will get incremented in the printf statement.

Bazooka
  • 1,428
  • 4
  • 15
  • 24
0

Whenever we are assigning a constant to a pointer, it should be like int const * p=(unsigned int*)5. If you are lucky, 5 would be in your program's address space. If not, then you get a seg fault. That's why it's undefined behavior. Check this for more details on int const, const int etc. const int = int const?

Community
  • 1
  • 1
Thunderman
  • 115
  • 1
  • 5