Range-based for loop with strings

usay

uSay

Posted on April 15, 2023

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
usay
uSay

Posted on April 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related