# Why aren't 2 chars equal?

• 04-25-2007
seraph
Why aren't 2 chars equal?
I'm new with c++ programming and i got this newb guestion.
I got 2 variables, char a[5] = "hola"; and char b[5] = "hola";.
The problem is that when i check them like this:
Code:

```char a[5] = "hola"; char b[5] = "hola"; if(a == b) { cout << "Hello to you too\n"; } else { cout << "No hello to you\n"; }```
it says "No hello to you".
So what i want to ask is why aren't those equal and how can i make variables a and b equal?
• 04-25-2007
KONI
You are not comparing two "chars" but actually you are comparing pointer to char arrays, which are two completely different things. Since you are not using the std::string type (that supports comparison using the == operation), you have to understand how C strings work.

In fact, a and b are pointers to the first element of each respective array. Imagine that they do not contain a specific character but rather an address to the location where the first character of the array is located. If the address of a is "0000" and the address of b is "1000", then when you write a==b, you effectively compare the two addresses, which, as you can see, are different.

If you want to compare two C strings, use the strcmp() function that does the job for you:

Code:

```char a[5] = "hola"; char b[5] = "hola"; if (strcmp(a,b) == 0) { cout << "Hello to you too\n"; } else { cout << "No hello to you\n"; }```
Since you are programming in C++, you could just write:
Code:

```std::string a, b; a = "hola"; b = "hola"; if(a == b) { cout << "Hello to you too\n"; } else { cout << "No hello to you\n"; }```
since then you're using the overloaded comparison operator of the string object.
• 04-25-2007
Salem
It's a good job you didn't try

char *a = "hola";
char *b = "hola";
if(a == b)

Which might be the right answer for entirely the wrong reason :)
• 04-25-2007
seraph
• 04-25-2007
Daved
If you are new to C++ you should not be using character arrays to store strings. Use the C++ string class instead.
• 04-25-2007
brewbuck
Quote:

Originally Posted by Salem
It's a good job you didn't try

char *a = "hola";
char *b = "hola";
if(a == b)

Which might be the right answer for entirely the wrong reason :)

Sometimes I use a string caching layer which inserts strings into a hash table and returns a pointer to the instance of the string in the hash. If you do this consistently, you CAN compare strings for equality by just checking if the pointers are equal :)