My IsIsogram

bool const UBullCowCartridge::IsIsogram(const FString& word) const
{
    for (int32 i = 0, j = i + 1; i < word.Len() - 1; ++i)
    {
        for (j = i + 1; j < word.Len(); ++j)
        {
            if (word[i] == word[j]) return false;
        }
    }
    return true;
}

Note j is initialized in the outer for loop to avoid allocating a new int each loop.

Perhaps unsurprisingly the compiler knows how for loops work.
What you have written generates the exact same assembly with all three major compilers, except with 0 optimisations enabled yours generates extra instructions due to the repeated i + 1.
https://godbolt.org/z/7gMeWr

So the lesson here is to stick with best practices which is to declare variables in the smallest possible scope (though obviously if you have profiling data that proves it’s better performance… it’s a guideline after all).

1 Like

Does it reinitialize that each time around? I was thinking it was more like the first time into the for loop it initializes the variables, does it reinitialize them each time?

Well this is kind of breaking the barrier of the language and the implementation.

Implementation-wise they’re ints so on registers and it would just reuse the same registers.

Language-wise j would go out of scope and be destroyed at it’s } when the condition fails.

Privacy & Terms