samedi 5 décembre 2020

Condition statements causing different outputs depending on if and how it is initialised

The following code:

int size = str1.size () - i;
if (size <= 0)
{
    str2 = 0;
}

When changed to this:

if (str1.size () - i <= 0)
{
    str2 = 0;
}

Causes an entirely different final output by the program. This occurs in isolation, meaning absolutely nothing about the code anywhere else is changed, yet this change causes something somewhere in the program to break. Why?

I see the same problem with a for loop, whereby I take the least significant digit of a number stored as a string, and I obtain that LSD via string[string.length() - 1 - i]. If I change the for loop from iterating up to string.length() - 1 from 0, to counting down to 0 from string.length() - 1, and change the string access to string[i], once again the program gives an entirely different output. Why?

Both these instances display alternate methods of reaching the same code logic, so what's going on behind the scenes that messes up how the program runs?

Aucun commentaire:

Enregistrer un commentaire