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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay