I was messing around and noticed something strange. You can actually do "a" + 2
and the program compiles fine, but doesn't output anything. However "a" + 32
says array subscript is above array bounds
.
Asked
Active
Viewed 1,170 times
0
-
6Hint: "a" is char array with size of 2 – Bryan Chen Aug 14 '14 at 02:34
-
"a" + 2 is also beyond bounds... a[0] holds the 'a', a[1] a NUL, and that's it. Trying to output `"a" + 2` has undefined behaviour. – Tony Delroy Aug 14 '14 at 02:50
-
Does this answer your question? [What's the behaviour of "" + number and why c++ compile it?](https://stackoverflow.com/questions/64174082/whats-the-behaviour-of-number-and-why-c-compile-it) – JaMiT Oct 04 '20 at 23:51
1 Answers
8
"a" is actually a const char[], but it can be converted without a cast to a const char* or to a char* and when you do math on pointers it works like array subscript syntax. So you're creating a new pointer which is farther along in the string. This reference on pointer arithmetic might be useful. If you do get a char* reference to the literal, it still is undefined to modify it (from experience it might crash if in read-only page, or might change all references where it is used).

Community
- 1
- 1

Jason Winnebeck
- 1,254
- 1
- 10
- 15
-
3`"a" is actually a const char*` - no it's not... it's a `const char[]` that undergoes an implicit Standard Conversion to `const char*` when necessary. – Tony Delroy Aug 14 '14 at 02:43
-
It was hard for me to tell, because MDSN reference (http://msdn.microsoft.com/en-us/library/8kc54dd5.aspx) only shows assignment to char*, but there are SO questions saying it's a const char[] (http://stackoverflow.com/questions/15508148/what-is-the-type-of-a-string-literal-in-c) but some confusion as to whether or not the string literal is const (because MSDN reference shows assignment to char*). But I think clearly the array can be assigned to a const char* or char* reference, and if it is a char*, you shouldn't modify it. I'll edit my post. – Jason Winnebeck Aug 14 '14 at 15:10
-
Assignment to a non-`const` `char*` was deprecated in C++98 and removed in C++11... been a long time since writable string literals were actually considered a reasonable compiler implementation choice, so even pre-C++11 code that compiled ok would tend to crash if an actual attempt was made to write through to the string literal. Also, it's noteworthy that `template
void f(const char (&a)[N]) { std::cout << N << '\n'; } ... f(a);` can print the # elements in array `a` because `a` really is still an array, not just an inherently dimensionless pointer. :-) – Tony Delroy Aug 15 '14 at 03:05