Main Content

AUTOSAR C++14 Rule A13-2-3

A relational operator shall return a boolean value

Since R2020a

Description

Rule Definition

A relational operator shall return a boolean value.

Rationale

The return value from relational operators of the C++ Standard Library can be directly checked to see if a relation is true or false. Overloads of the relational operator must be consistent with this usage. Otherwise, users of the overloaded relational operator might see unexpected results. See example below.

Polyspace Implementation

The checker flags overloads of relational operators that do not return a value of type bool.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class aClass {
    int val;
public:
    aClass(int initVal) {
        val = initVal;
    }
    bool operator<=(aClass const& comparingObj )  noexcept{ //Compliant
        return(this->val <= comparingObj.val);
    }
    int operator>=(aClass const& comparingObj ) noexcept { //Noncompliant
        return(this->val <= comparingObj.val? -1:1);
    }
};

void func() {
    aClass anObj(0), anotherObj(1);
    if(anObj <= anotherObj) {
        /* Do something */
    }
    if(anObj >= anotherObj) {
        /* Do something else */
    }
}

In this example, the overload of operator<= returns a boolean value but the overload of operator>= does not return a boolean value. However, in function func, the operators <= and >= are used as if a boolean value is returned from the overloaded operators. Because the overload of operator>= does not return the value zero, the second if statement is always true, a result that you might not expect.

Check Information

Group: Overloading
Category: Required, Automated

Version History

Introduced in R2020a