-1

I just wrote following code and it's working with g++. It shouldn't work. Why is it working?

#include <iostream>
using namespace std;

int main()
{
        //char const *cstr;
        const char *cstr;
        char *cptr;
        std::cin>>cptr;
        cstr = cptr;
        cstr = "CPP";
        cout<<cstr;
        return 0;
}

as it is apparent that cstr is const so it's modification in line cstr = "CPP"; should not work, but it is working. Why?

StewieGGriffin
  • 349
  • 1
  • 4
  • 14

4 Answers4

4

cstr is a non-constant pointer to a constant. It can be assigned to and reassigned.

A constant pointer to a constant would be char const* const cstr.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
0

This code causes undefined behaviour (if there is any input on cin):

std::cin>>cptr;

The meaning of that code is to read characters from cin and write them into the space pointed to by cptr. But you did not initialize cptr.

When a program has undefined behaviour, anything can happen, including "working as expected".

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
0
const char *cstr;

as it is apparent that cstr is const

No, it isn't.

It is non-const, but the thing that it points to is const.

Furthermore, you're attempting to read into a char buffer that does not exist.

Stop using C-strings, and get yourself some shiny std::strings instead.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

To anyone who gets confused like I do when it comes to pointers with const declarations, use http://cdecl.org/.

StewieGGriffin
  • 349
  • 1
  • 4
  • 14