0

This question already has an answer here:

I'm writing a function (or operator==() in C++), comparing two objects. The code looks like this:

bool operator==(const Obj& copy1, const Obj& copy2)
{
    if(copy1.a!=copy2.a)
        return false;
    if(copy1.b!=copy2.b)
        return false;
    if(copy1.c!=copy2.c)
        return false;
    return true;
}

There may be many more data members to compare, and not all members present in Obj are to be compared, so using memcmp() isn't an option. There also might be more complicated tests than just equality of the members. Now there's another way:

bool operator==(const Obj& copy1, const Obj& copy2)
{
    return (copy1.a==copy2.a &&
            copy1.b==copy2.b &&
            copy1.c==copy2.c);
}

The first way seems more verbose, but also easier to modify, while the second seems somewhat fragile (can't explain why, just gut feeling), but looks a lot simpler.

What is a better way? Is there any real difference in readability or maintainability of these approaches?

marked as duplicate by gnat, Daenyth, user53019, durron597, user40980 May 30 '15 at 0:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I'm guessing the third compare should be against c? – Telastyn May 28 '15 at 13:14
  • @Telastyn ah, right, fixed. – Ruslan May 28 '15 at 13:15
  • Use the second, and see if you can't get rid of the more complex conditions by wrapping the relevant data in a separate class that itself overloads == – Sebastian Redl May 28 '15 at 13:18
1

The first example is bad/fragile due to a lack of braces. Such code would not pass code review at the majority of places I've worked. If you add braces (making the conditional a single line if preferred), then they're fairly equivalent from what I've seen. Many places will prefer the first since conditionals can be used everywhere, but the complex expression can only be used when its parts are relatively simple/similar. But they wouldn't object to the second version in this sort of case, and it won't lead to maintenance problems.

  • +1 One could either omit the braces, or write it in one line. But the form above is double inconsequent. We all remember Apple's Goto-Fail. – Thomas Junk May 28 '15 at 13:16
  • By braces do you mean {} or parentheses ()? I don't quite understand, lack of what you are talking about. Do you mean I should write {return false;} instead, or (copy1.a==copy2.a)&&...? – Ruslan May 28 '15 at 13:33
  • @ruslan - if(blah){stuff;} rather than if(blah)stuff;. programmers.stackexchange.com/questions/16528/… – Telastyn May 28 '15 at 14:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.