Why this odd behavior on my code

Revision en2, by LM10xLeoMessi, 2025-02-12 10:39:26

i was writing this code and faced this unknown behavior.

void solve(){ string s = "a"; for(int i = 0; i < s.size() — 1; i++){ cout << "1st for loop\n"; if(s[i] == s[i + 1]){ cout << s[i] << s[i + 1] << '\n'; return; } } for(int i = 0; i < s.size() — 2; i++){ cout << "2nd for loop " << i << '\n'; if(s[i] != s[i + 1] and s[i] != s[i + 2] and s[i + 1] != s[i + 2]){ cout << s[i] << s[i + 1] << s[i + 2] << '\n'; return; } } cout << -1; }

shouldn't it print -1? then why it enters into second for loop as the size of my string is 1? Can anyone help me to understand this behavior?

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English LM10xLeoMessi 2025-02-12 10:41:03 16
en3 English LM10xLeoMessi 2025-02-12 10:39:53 20
en2 English LM10xLeoMessi 2025-02-12 10:39:26 18
en1 English LM10xLeoMessi 2025-02-12 10:39:00 758 Initial revision (published)