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
x [y]
*(x + y)
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
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.
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!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
A "fun" side effect of the fact that the C++ (and C) subscript operator is just pointer arithmetic means that
is actually valid C++ 😆.
Because
x [y]
is the same as*(x + y)
, that means thatis just the same as
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 doSo I guess that means the original example of
can be rewritten as
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
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.
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!