DEV Community

Discussion on: A Weird Way to Substring in C++

Collapse
 
barney_wilks profile image
Barney Wilks

A "fun" side effect of the fact that the C++ (and C) subscript operator is just pointer arithmetic means that

const char* array[] = { "Well", "This", "Is", "Strange" };

// value contains "Strange"
const char* value = (1 + 1) [array + 1];

is actually valid C++ 😆.

Because x [y] is the same as *(x + y), that means that

const char* x = (1 + 1) [array + 1];

is just the same as

const char* x = *(1 + 1 + array + 1);
// Or
const char* x = *(array + 3); // array [3]

It's worth only noting that this works where the subscript operator does use pointer arithmetic (C style arrays and pointers mostly I think) and not where the [] operator is overloaded - so you can't do

std::string v = "Hello World!";
char second_letter = 1 [v];

So I guess that means the original example of

string s = &"Hello, World"[7];
string ss = &s[2];

can be rewritten as

std::string s = & (2 * 3 + 1) ["Hello, World!" - 1];

if you were so inclined 😆.
Sometimes I worry about C++ - it doesn't exactly help itself at times... 😄

Obligatory godbolt for this:
godbolt.org/z/nHJOgs

Collapse
 
codemouse92 profile image
Jason C. McDonald

Sometimes I worry about C++ - it doesn't exactly help itself at times... 😄

Yes, but at least we get to play with esoteric hackery without needing a different language.

...and sometimes, ever so rarely, if the stars are aligned, that hackery comes in handy.

Collapse
 
therealdarkmage profile image
darkmage

I knew about the pointer arithmetic aspect from college, but I had no idea you could also do it with string constants! Thank you for the explanation!