std::basic_string::operator[] in C++

Returns a reference to the character at specified location pos. No bounds checking is performed. If pos > size(), the behavior is undefined.

Syntax :

reference operator[] (size_type pos);
const_reference operator[] (size_type pos) const;
Parameters :
pos - position of the character to return
Return value :
Reference to the requested character
Exceptions :
No exception is thrown




/* CPP program to access
   a character through
   std::basic_string::operator[] */
#include <iostream>
//Driver code
int main()
    //String with valid indices from 0 to 2
    std::string str = "abc";
    //Printing size of string
    std::cout << "string size = " << str.size() << '\n';
    //Accessing element at index 2
    std::cout << "Element : " << str[2];



string size = 3
Element : c

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.