0
    #include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {

   char input[] = "Hello!";
   for(int i=strlen(input);i>=0;i--){
       input[i+2] = input[i];
   }
   input[1] = 'i';
   input[0] = 'H';
   cout<<input<<endl;
    return 0;
}

I tried this sample program to shift the string by 2 places and appended a Hi infront. The code works perfectly fine. Could someone please explain how the for loop runs i.e. how does the shifting take place? I made an array of 6 elements and later I am accessing the 8th index, still it works fine. How come ?

  • 2
    You have undefined behavior in your code because you access out of bounds indices of input – drescherjm Mar 02 '21 at 14:56
  • ***I made an array of 6 elements and later I am accessing the 8th index, still it works fine*** Unfortunately with UB sometimes you get the result you expected even though the code is broken. This is the worst behavior in undefined behavior because it gives you a false sense that your code is correct. – drescherjm Mar 02 '21 at 14:58

0 Answers0