Character Check Pt.2

I decided to show what I did verses what the instructor did as a sort of comparison for interest sake:

// Instructors Code
   
    for (int32 Index = 0; Index < Word.Len(); Index++)
    {
        for (int32 Comparison = Index + 1; Comparison < Word.Len(); Comparison++)
        {
            if (Word[Index] == Word[Comparison])
            return false;
        }
    }
    return true;

//My Multi-character checking code    
    // int32 Index = 0; 
    // int32 Comparison = Index + 1;

    // for (; Comparison < Word.Len(); Comparison++)
    // {
    //     for (;Comparison < Word.Len(); Index++)
    //     {
    //         if (Word[Index] == Word[Comparison])
    //         {
    //             return false;
    //         }
    //     }
    // }
    // return true;

I found that mine worked, but that the instructors was more elegant. The issue I found with mine was when he mentioned of a 3rd way to implement our variables into the code. The Index was kept outside of for loops, but the Comparison was placed within the first loops conditions. Now my Comparison variables stopped working.

Why? Because they were no longer in scope. When I had it before the loop variables it made it larger than loop’s scope, making it accessible at any point in the loop despite its position.

This brings me to the next part of my code: I had the Comparison++ and Index++ switched around. However, since both variables were declared and defined outside the loop this did not seem to matter. My code worked fine anyway.

Possible issues? I suspect if I wanted to run multiple, yet separate comparisons in one function, should I want to use both the variables Index and Comparison in those loops, it may change the data on me and give me errors in my other checks. If they are confined to their own little corner, they will keep within scope and not touch any other instance that may use the same names.

1 Like

I love your explanation. You understood that yours worked and even if the instructor was more elegant you still found a way to do that works and will probably even find a way better than the instructor.

I do not have enough experience with code to agree or disagree :). It might be as some others have said in the forum: depends on the situation. :+1:

Privacy & Terms