tags:

views:

361

answers:

5

I have two variables:

char charTime[] = "TIME";
char buf[] = "SOMETHINGELSE";

I want to check if these two are equal... using charTime == buf doesn't work.

What should I use, and can someone explain why using == doesn't work?

Would this action be different in C and C++?

A: 

Check them in a for loop. Get the ASCII numbers for each char once they change they're not equal.

Is this the simplest way of doing it? Must be something better?
rksprst
There is refer to Johannes Schaub - litb post.
+9  A: 
char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";

C++ and C (remove std:: for C):

bool equal = (std::strcmp(charTime, buf) == 0);

But the true C++ way:

std::string charTime = "TIME", buf = "SOMETHINGELSE";
bool equal = (charTime == buf);

Using == does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.

Johannes Schaub - litb
This is because C++ allows operator overloading, which overloads the `==` to actually do a content-comparison, instead the "default" `char[]`'s `==`, which is reference-comparison.
Pindatjuh
Wouldn't you need to #define your bool type for C as well?
Mimisbrunnr
@mim: C99 has a `bool` type. So you would probably only need to define it with MSVC.
Joey
@Mim, as Johannes Rössel says, C99 has a `bool` type. You need to include `<stdbool.h>` to be able to use `bool` though, or you need to use the built-in type `_Bool` (which the `bool` will be a `#define` for) or just plain `int`.
Johannes Schaub - litb
+3  A: 

In c you could use the strcmp function from string.h, it returns 0 if they are equal

#include <string.h>

if( !strcmp( charTime, buf ))
Mimisbrunnr
A: 

You are checking the identity charTime and buf. To check the equality, loop over each character in one array and compare them with the related character in the other array.

lajuette
or use strcmp...
lajuette
+1  A: 

In an expression using == the names of char arrays decay into char* pointing to the start of their respective arrays. The comparison is then perform in terms of the values of the pointers themselves and not the actual contents of the arrays.

== will only return true for two pointers pointing to the same location and false otherwise, even if they are pointing to two arrays with identical contents.

What you need is the standard library function strcmp. This expression evaluates as true if the arrays contain the same contents (up to the terminating null character which must be present in both arrays fro strcmp to work safely).

strcmp(charTime, buf) == 0
Charles Bailey