Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use strcmp instead of == in C++?

Tags:

c++

strcmp

I wonder my code works perfectly fine either using strcmp or simply == in C++ for comparing 2 char arrays. Can any one justify the reason of using strcmp instead of ==;

like image 624
Fawad Nasim Avatar asked Mar 22 '14 03:03

Fawad Nasim


People also ask

Why do we use strcmp in C?

strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.

When would you use a strncmp?

Presuming that the string in message is supposed to be null-terminated, the only reason to use strncmp() here rather than strcmp() would be to be to prevent it looking beyond the end of message , in the case where message is not null-terminated.

What is the use of strcmp () function?

strcmp compares two character strings ( str1 and str2 ) using the standard EBCDIC collating sequence. The return value has the same relationship to 0 as str1 has to str2 . If two strings are equal up to the point at which one terminates (that is, contains a null character), the longer string is considered greater.

What can I use instead of strcmp?

With string arrays, you can use relational operators ( == , ~= , < , > , <= , >= ) instead of strcmp . You can compare and sort string arrays just as you can with numeric arrays.


2 Answers

strcmp compares the actual C-string content, while using == between two C-string is asking if these two char pointers point to the same position.

If we have some C-string defined as following:

char string_a[] = "foo";
char string_b[] = "foo";
char * string_c = string_a;

strcmp(string_a, string_b) == 0 would return true, while string_a == string_b would return false. Only when "comparing" string_a and string_c using == would return true.

If you want to compare the actual contents of two C-string but not whether they are just alias of each other, use strcmp.

For a side note: if you are using C++ instead of C as your question tag shows, then you should use std::string. For example,

std::string string_d = "bar";
std::string string_e = "bar";

then string_d == string_e would return true. string_d.compare(string_e) would return 0, which is the C++ version of strcmp.

like image 136
WiSaGaN Avatar answered Oct 07 '22 02:10

WiSaGaN


One advantage of using strcmp is that....it will return < 0 if str1 is less than str2

0 if str1 is greater than str2 and 0 if they are equal.

but if you use simply == it will only return either true or false.

like image 1
psj01 Avatar answered Oct 07 '22 03:10

psj01