jlcv
jlcv

Reputation: 1808

Pointer issues: Odd function output when one line of code is added

In my textbook is a function called streq that checks to see if a string is equal. I copied this code and decided to add cout << *s1 << endl; to see what it is printing out before returning false. However, what I notice is that if both input strings are equal and I have the extra code I added, it will return false.

#include <iostream>
using namespace std;

bool streq(const char* s1, const char* s2);

int main()
{
    const char A [] = "Hello";
    const char B [] = "Hello";

    cout << streq(A,B) << endl;
}

bool streq(const char* s1, const char* s2)
{    
    int count = 0;

    while (*s1 != 0 && *s2 != 0)
        if (*s1++ != *s2++)
            cout << *s1 <<  endl;
            return false;
        count++;
    return (*s1 == *s2);
}

However, if I comment out the code I added, the function will work properly and return true (1). Does anyone know what the issue is here?

Upvotes: 0

Views: 80

Answers (1)

Yu Hao
Yu Hao

Reputation: 122453

Despite your indentation, this code

if (*s1++ != *s2++)
    cout << *s1 <<  endl;
    return false;

is equivalent to:

if (*s1++ != *s2++)
{
    cout << *s1 <<  endl;
}
return false;

That's why your modification changed the logic of the program. if condition controls the next statement, one statement only. You need to use a block if you need multiple statement.

if (*s1++ != *s2++)
{
    cout << *s1 <<  endl;
    return false;
}

This is exactly why some people choose to always use a block with if and else, even when there's only one statement follows. It's less error-prone when you need to add more statement later.

Upvotes: 6

Related Questions