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

风格不统一 提交于 2021-02-18 21:01:26

问题


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


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/22572987/why-use-strcmp-instead-of-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!