Why doesn't this return true?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()
{
    char word1[]="hello",word2[]="hello"
    if(word1==word2)
        cout<<"word1 equals word2";
    else
        cout<<"word1 does not equal word2";
}


The output is "word1 does not equal word2". Is this because the if statement is checking to see if the addresses of the arrays are equal, and not the actual content of the arrays?
Yes, the value of word1 and word2 are memory addresses. Try this instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char word1[] = "hello";
    char word2[] = "hello";

    if(!strcmp(word1, word2))
        cout << "word1 equals word2";
    else
        cout << "word1 does not equal word2";
		
    return 0;
}


strcmp returns 0 if two cstrings are equal.
Last edited on
Okay, thanks for clearing that up.
Topic archived. No new replies allowed.