if (0 == strcmp(val1,val2)) or (strcmp(val1,val2) == 0)
Any studies or style guides that support one these styles over the other?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
My preference is strcmp(x, y) == 0. The reason for this is that this style uses the same operator that would be naturally used in the expression x == y (that just compares pointers for equality and thus doesn't do what you want).
Also, you can do inequality comparisons as well: if you want to check whether x < y, you can do it by strcmp(x, y) < 0. The operator is the same.
Now, the only reason for 0 == strcmp(x, y) is that some old compilers may not warn if you use the = operator inside an if statement. The problem with this way is that if you want to check x < y, you do it by 0 > strcmp(x, y) so the operator just switched to the opposite operator. Not at all intuitive. Because modern compilers warn about "if (x = 0)" there is no reason to use these so-called "Yoda conditions".
Also, !strcmp(x,y) looks like "x not equal with y", which is not what it does. So, I would recommend not to use the ! operator with strcmp().
One mnemonic I find useful is "not means naught" whenever I am converting an integer into a bool.
As to the unnaturalness, unfortunately you have to get over it, because it is an example of idiomatic usage of the language.
If you are allowed to define utility functions, you can wrap the whole thing into new functions like
bool Equals(...) and
bool EqualsIgnoreCase(...), which would make a C#-turns-C++ programmer happy.
However, unless your entire team agrees, and your project's stakeholders also accept the consequence that the code base doesn't conform to C++ idioms, borrowing heavily from the idioms of a different language is ill-advised. It prevents the stakeholders from choosing to open-source the project, or making it difficult to recruit more experienced C++ developers into the project.