What am I missing here?

Hi everyone! I'm a little confused here as basically when i run the code bellow with len1 being longer than len2 the if(len1 << len2) still executes. I have debugged and can see that len1 for example is unsigned long long 7 and len2 is unsigned long long 3

what am I missing here, can anyone help me out? I would really appreciate it

also sorry if I've messed something up format wise I'm new here :)

oh and i'm using the appropriate using std::cout etc and have includes iostream and string as well

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    string s5, s6;
    cout << "enter 2 words: ";
    cin >> s5 >> s6;

    auto len1 = s5.length();
    auto len2 = s6.length();

    if(len1 == len2)
    {
        cout << "The words are the same length!";
    }
    else
    {
        if(len1 << len2)
        {
            cout << s6 << " Is longer than " << s5;
        }
        else
        {
            cout << s5 << " Is longer than " << s6;
        }
    }
< is the less than operator.
<< is the left bitshift operator.
if(len1 << len2)

This says:
shift len1 by len2 bits to the left. If that is not zero.. {things} else {other things}.

many, many things can be reduced to a 0 or not zero boolean result even when the code is borked up, as seen here.
& and | are also bitwise and will do things you do not expect if put into a condition unintentionally. ^ is also a bitwise operator and never a power/exponent in c++ Less seen, ~ as well, but its not used anywhere else.
Last edited on
Also, it arguably reads better if you remove the unnecessary block & indentation for your else block.

1
2
3
4
5
6
7
8
9
10
11
12
    if(len1 == len2)
    {
        cout << "The words are the same length!";
    }
    else if(len1 < len2)
    {
        cout << s6 << " Is longer than " << s5;
    }
    else
    {
        cout << s5 << " Is longer than " << s6;
    }


Edit: Also you are mixing up your if and else. 's5', 'len1', etc. are confusing variable names to keep track of. Surely they must represent something more meaningful?
Last edited on
Topic archived. No new replies allowed.