Home > Back-end >  Restructuring of an if
Restructuring of an if

Time:04-10

Can you help me rearrange this code? cLion suggests a warning to the accolade of the first if [Clang-Ti dy: Repeated branch in conditional chain], I do not understand why. P.S I try to compare 2 calendar dates, to later set the maximum date and the minimum date.(d - day, m - mounth and y - year).

if (d1.y < d2.y) {
    return -1;
} else if (d1.y == d2.y && d1.m < d2.m) {
    return -1;
} else if (d1.y == d2.y) {
    if (d1.m == d2.m) {
        if (d1.d < d2.d) {
            return -1;
        }
    }
} else {
    return 1;
}
return 0;

CodePudding user response:

There are numerous ways to write this code. Here is one that attempts to show the comparisons clearly:

//  If years differ, return comparison based on that.
if      (d1.y < d2.y)
    return -1;
else if (d1.y > d2.y)
    return  1;

//  Otherwise, if months differ, return comparison based on that.
else if (d1.m < d2.m)
    return -1;
else if (d1.m > d2.m)
    return  1;

//  Otherwise, if days differ, return comparison based on that.
else if (d1.d < d2.d)
    return -1;
else if (d1.d > d2.d)
    return  1;

//  Otherwise, all components are equal, so return equality.
else
    return  0;

CodePudding user response:

If I had to guess, your d1 and d2 objects are "dates". Hence, the members, y (year), m (month), and d (day). And your comparison logic seems to test if d1 is a later date than d2. I'm guessing for a sort routine like qsort.

Hence, a quick conversion to integer might be cleaner.

long date1 = (d1.y << 16) | (d1.m << 8) | (d1.d);
long date2 = (d2.y << 16) | (d2.m << 8) | (d2.d);

Then you can test like this:

if (date1 == date2) return 0;
if (date1 > date2) return 1;
return -1;

And if this is for a qsort like comparison function where you can return anything greater than 0 for d1>d2, and anything less than zero for d1<d2, then you can simply say this:

return date1-date2;
  •  Tags:  
  • c
  • Related