DEV Community

uSay
uSay

Posted on

Range-based for loop with strings

This is post just for myself as a memo.

I am confused when I wrote range-based for loop, directly putting string as a target.
Putting string as the target of range-based for loop flashed into my mind when I practiced hashmap like:

int cnt = 0;
bool flag = true;
  while(flag){
    for(char &e: "balloon"){
      map[e]--;
      if(map[e] < 0) flag = false;
      }
      if(flag) cnt++;
    }
Enter fullscreen mode Exit fullscreen mode

However, this while loop finished after the 'n'.
I had no idea about this phenomenon.
This is why, I tested and tried to confirm their movement.

int main(void){
    // Your code here!
    for(auto e: "TestStrings"){
        cout << e << ':';
        printf("%X ", e);
    }
    cout << endl;
    string s = "TestStrings";
    for(auto &e: s){
        cout << e << ':';
        printf("%X ", e);
    }
}
Enter fullscreen mode Exit fullscreen mode

This code shows:

// T:54 e:65 s:73 t:74 S:53 t:74 r:72 i:69 n:6E g:67 s:73 :0 
// T:54 e:65 s:73 t:74 S:53 t:74 r:72 i:69 n:6E g:67 s:73
Enter fullscreen mode Exit fullscreen mode

Conclusion: The former has a NULL at its end of the line.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay