Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const - Shouldn't it not change

In running this C++ code, I expected the output to be Abc, but, it was FFF, why is that? Isn't name pointing to a constant char?

#include <iostream>
int main()
{
    const char* name = "Abc";
    name = "FFF";
    std::cout<<name<<std::endl;
    return 0;
}
like image 737
Simplicity Avatar asked Jan 28 '11 10:01

Simplicity


2 Answers

Yes, it's pointing to a const char as you say, but it is not a constant pointer. You are changing what you are pointing to, not the contents of what you are pointing to. In other words, the memory holding "Abc" still holds the characters "Abc" after you reassign the pointer.

For a constant pointer, you want const char* const name = "Abc";. In this case, it won't compile since you can't change what the pointer points to.

In general, with const and pointers in C++, you can read the type name from right-to-left to get a feel for what is going on. For example, in the const char* const case, you can read this as "a constant pointer to a character constant". A little weird, but it works.

like image 118
Chris Schmich Avatar answered Oct 09 '22 17:10

Chris Schmich


const char* name = "Abc"; -> Non const pointer-> name, but data (Abc) is constant

name = "FFF" -> changing pointer(name) to point to FFF.

char *p              = "Hello";          // non-const pointer,
                                         // non-const data
const char *p        = "Hello";          // non-const pointer,
                                         // const data
char * const p       = "Hello";          // const pointer,
                                         // non-const data
const char * const p = "Hello";          // const pointer,
                                         // const data
like image 20
DumbCoder Avatar answered Oct 09 '22 17:10

DumbCoder