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 ==
;
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.
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.
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.
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.
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
.
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.
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