Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare equality of char[] in C

Tags:

c++

c

equality

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

like image 728
rksprst Avatar asked Mar 13 '10 23:03

rksprst


People also ask

What does char [] mean in 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.

Can you compare char arrays in C?

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.

Can I use == to compare char?

The char type is a primitive, like int, so we use == and != to compare chars.

How do you check if a char is equal to another char in C?

C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.


2 Answers

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.

like image 141
Johannes Schaub - litb Avatar answered Oct 18 '22 17:10

Johannes Schaub - litb


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 ))
like image 32
zellio Avatar answered Oct 18 '22 17:10

zellio