Question about a warning message
Joshua Scoggins
Josh.Scoggins@parasoft.com
Thu Sep 6 18:53:00 GMT 2018
Hello,
On 09/06/2018 10:58 AM, Juan Cabrera wrote:
> Hello,
>
> I'm getting a "control reaches end of non-void function" warning
> message on the following code (tested with gcc version 7.3 and above):
>
> enum class T { A, B };
>
> int f(T t) {
> switch (t) {
> case T::A: return 10;
> case T::B: return 20;
> }
> }
>
>
> Shouldn't the compiler assume that function `f` always returns
> something for all valid inputs `t`? (Given that the parameter `t` is
> of type `T` which is an enum class and the siwtch statement covers all
> the enum values).
>
No the compiler should not assume this as an enum class does not protect
you from invalid input and casts (only implicit conversion is
prevented). Here is an example:
int performOperation() {
return f(T::A) + f(T::B) + f(static_cast<T>(3));
}
The legal values for T are A and B which are 0 and 1 respectively. Three
is not a legal value for type T but it can be cast into it. Thus an
invisible fallthrough will happen and an undefined result will be
returned from f in the case of 3 (or any other number).
> Regards,
> Juan.
>
--
Josh Scoggins
More information about the Gcc-help
mailing list