Undefined behavior of a c++ program

  c++, c++14

I have listed 2 codes below

CODE 1:

int  main()
{       
int z=0 ,a[100];    
for(int i=10;i<=30;i++)
{
if(palindrome(i))
a[++z]=i;
}    
cout<<"value of z = "<<z<<endl;    
}

CODE 2:

int  main()
{
int z=0 ,a[100];

for(int i=10;i<=30;i++)
{
if(palindrome(i))
a[++z]=i;
cout<<z<<endl;   //  JUST ADDED THIS EXTRA LINE
}

cout<<"value of z = "<<z<<endl;
}

#Note:

the function palindrome return 0 if the number given is not a palindrome

function palindrome is as follows

int palindrome (int n)
{
    int rev;
    int n1=n;
    while(n!=0)
    {
        int t=n%10;
        rev = (rev*10) + t;
        n/=10;
    }
    
    if(rev!=n1)
    return 0;   
}

OUTPUT FOR CODE 1: value of z = 0

OUTPUT FOR CODE 2:

0
1
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
value of z = 2

can anyone explain why addition of cout<<z<<endl; inside the loop creating such a drastic change in value of final z ?

Source: Windows Questions C++

LEAVE A COMMENT