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++?
The abbreviation char is used as a reserved keyword in some programming languages, such as C, C++, C#, and Java. It is short for character, which is a data type that holds one character (letter, number, etc.) of data.
The strcmp() function is a built-in library function in the C language. Its basic role is to compare two character arrays or strings terminated by null value (C-strings) lexicographically. The strcmp() function is called using two character arrays as parameters and returns an integer value.
The char type is a primitive, like int, so we use == and != to compare chars.
C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
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.
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 ))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With