Why 2["abc"] outputs 'c'? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

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

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

20th Nov 2019, 12:31 AM
Theodora Danciulescu (Oeht)
Theodora Danciulescu (Oeht) - avatar
4 Answers
+ 6
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
20th Nov 2019, 1:43 AM
MO ELomari
+ 2
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?
20th Nov 2019, 12:43 AM
Theodora Danciulescu (Oeht)
Theodora Danciulescu (Oeht) - avatar
0
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 ?
20th Nov 2019, 12:37 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
- 1
I can't answer, I'm not very used to C++, I'll leave it to people who know more about it.
20th Nov 2019, 12:51 AM
Aymane Boukrouh
Aymane Boukrouh - avatar