-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
  • 163
  • 3
  • 13

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
  • 125,859
  • 15
  • 164
  • 254
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
  • 134,614
  • 21
  • 188
  • 335
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
  • 369,052
  • 73
  • 620
  • 1,021
0

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

StewieGGriffin
  • 163
  • 3
  • 13