Why use strcmp instead of == in C++?
Asked Answered
M

2

13

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

Mer answered 22/3, 2014 at 3:13 Comment(3)
Do you have an example of your code that works fine with both == and strcmp?Alfred
char abc1[10] = "Apple"; char abc2[10]="Mango"; if (abc1 == abc2) cout << "Equal "; else cout << "Not equal";Mer
However now I get clear that == points to same location. i was confusing with NotEqual result.Mer
G
22

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.

Gord answered 22/3, 2014 at 3:21 Comment(2)
note: this doesn't apply to std::string (in case ANYONE possibly doubted)Anticyclone
+1 beat me to it due to writing an example to show OP. No need to write another answer since you got it all already, just gonna leave the example here (with variables renamed to your versions).Tactful
D
2

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.

Drisko answered 22/3, 2014 at 3:26 Comment(1)
it will return bool for different comparision.Argentite

© 2022 - 2024 — McMap. All rights reserved.