0

Is the following code correct?

constexpr char s[] = "a, bb, ccc";
static const char * s1 = s;
char * s2 = const_cast<char *>(s1);
s2[5] = 'x';

my first idea was that 's' exists only at compile time and 's1' probably is some kind of a copy of 's', but probably it is not quite correct because line 2 does not compile without 'const':

static char * s1 = s;

The error with MSCV2017 is: 'initializing': cannot convert from 'const char [11]' to 'char [11]'.

so it is not clear what is the relation between 's' and 's1'? Do they reference the same string literal?

1
  • Note that the c++17 tag is for the C++17 standard, not about MSVC2017 (that would be the visual-studio-2017 tag). Commented Apr 8, 2019 at 11:54

2 Answers 2

2

The definition

static const char * s1 = s;

is equal to

static const char * s1 = &s[0];

That is, you make s1 point to the first element of s, that's all. There's no "copy" being made.

That's why you can't use pointers to non-const (i.e. char *) since s1 will point to constant data.

And that's also why s2[5] = 'x' will lead to undefined behavior as you attempt to modify constant data.

Sign up to request clarification or add additional context in comments.

10 Comments

@AlexeyStarinsky It does not even compile error: lvalue required as left operand of assignment
@Tetix OP missed a dereference or OP could have used a reference directly, but the point is that you cannot modify a.
@AlexeyStarinsky Yes that's UB. Any attempt to modify constant data leads to UB.
@AlexeyStarinsky Any use of const_cast should be a red flag that there's something bad going on. As would old C-style casts.
@alexey if you have a pointer to const or reference to const, and you know the data actually isn't const, const cast lets you safely cast it away. If you are wrong, it is UB. You can also add const with const cast.
|
1

my first idea was that 's' exists only at compile time

No, it also exists at run-time. constexpr does not mean "only at compile-time". What it means here is "s must be initialized with a constant expression" (a compile-time constant, basically), which means itself can be used in constant expressions, too.

's1' probably is some kind of a copy of 's'

s1 simply points to the first character of the s array. It is not a copy of the contents of the array.

line 2 does not compile without 'const':

You can't do that without const_cast -- but you wouldn't want anyway, because it is undefined behavior to modify a originally-const variable (which s is).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.