Why 2["abc"] outputs 'c'? | SoloLearn: Learn to code for FREE!


Why 2["abc"] outputs 'c'?

How is the c++ compiler working with that and why does this exists? When is it useful?

11/20/2019 12:31:20 AM

Theodora Danciulescu (Oeht)

4 Answers

New Answer


the compiler converts the array operation in pointers before accessing the array elements, which means all of the following expressions mean same thing *("abc"+2), "abc"[2], 2["abc"]: https://code.sololearn.com/cUE4lD7fokb9/#c


I don't understand how could this simplified syntax could be useful. If you have a string variable between the square brackets, it won't compile anymore. And also, I don't understand how the compilator works with that. For list indexing ( e.g. a[5]) the operator '[ ]' will make its job to return the content from memory addrress a+5. But how is the addressing done in this syntax?


What do you not understand in that ? It's just basic list indexing, are you asking about the purpose of the simplified syntax only, or the purpose of list indexing in general ?


I can't answer, I'm not very used to C++, I'll leave it to people who know more about it.