Compare equality of char[] in C

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++?


Solution 1:

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.

Solution 2:

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 ))

Solution 3:

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