Opened 3 years ago

Last modified 3 years ago

#10731 new defect

False positive missingReturn in uncompilable function

Reported by: ptomato Owned by: noone
Priority: Normal Milestone:
Component: False positive Version:
Keywords: missingReturn valueflow Cc: ptomato

Description

bug.cpp:

#include <type_traits>
template<T>
bool f(T) {
    static_assert(std::is_arithmetic_v<T>);
    if constexpr (std::is_arithmetic_v<T>)
        return true;
}

Output:

$ cppcheck bug.cpp                                                                                                              
Checking bug.cpp ...
bug.cpp:6:0: error: Found a exit path from function with non-void return type that has missing return statement [missingReturn]
        return true;
^

If the static assertion fails, then the function should never be compiled, so I think it's a false positive that the return statement is missing.

Observed with cppcheck 2.6.

Change History (3)

comment:1 by Daniel Marjamäki, 3 years ago

I wonder.. It is not obvious to me why you have if constexpr (std::is_arithmetic_v<T>). Can it be changed to if constexpr (true) since a false condition will never be compiled?

Last edited 3 years ago by Daniel Marjamäki (previous) (diff)

comment:2 by ptomato, 3 years ago

Hah, maybe I reduced the minimal example _too_ much :-)

How about this one?

#include <type_traits>
template<T>
bool f(T) {
    static_assert(std::is_arithmetic_v<T> || std::is_floating_point_v<T>);
    if constexpr (std::is_arithmetic_v<T>)
        return true;
    if constexpr (std::is_floating_point_v<T>)
        return false;
}

This way, the condition is not always true but there is no possible missingReturn.

comment:3 by chrchr, 3 years ago

Keywords: missingReturn valueflow added

#11204 was closed as a duplicate.

Note: See TracTickets for help on using tickets.