Re: Question about a warning message

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 2018-09-07 11:06 +0200, David Brown wrote:
> On 06/09/18 21:29, Juan Cabrera wrote:
> > Hello!
> > 
> > Thank you for your answers.
> > I'm aware that you can cast anything into an `enum class` but I
> > thought that casting a non valid enum-class value into an enum-class
> > was itself "wrong" or "unedfined behavior" or something like that :D.
> > 
> > I just checked and it looks like clang does not emit a warning in this case.
> > 
> > I guess I'll have to add a return statement to that function to keep
> > the compiler from complaning :D
> > 
> 
> It is usually not a good idea to change code just to stop the compiler
> from complaining.  Unless it is a false positive warning where you know
> the code is good, listen to the compiler.
> 
> To me, there are two choices.  One is that you believe "f" /might/ be
> called with a T that is not A or B.  In that case, you should handle it
> appropriately - not just have a fake return to keep the compiler quiet.
>  For example:
> 
> int f(T t) {
> 	switch (t) {
> 		case T::A : return 10;
> 		case T::B : return 20;
> 	}
> 	throw std::runtime_error("Calling f with a bad t");
> }
> 
> Alternatively, if you are sure that "f" will never be called with an
> inappropriate t, tell the compiler that:
> 
> int f(T t) {
> 	switch (t) {
> 		case T::A : return 10;
> 		case T::B : return 20;
> 	}
> 	__builtin_unreachable();
> }

I usually write something like

    #ifdef NDEBUG
    #define unreachable() __builtin_unreachable()
    #else
    #define unreachable() __builtin_trap()
    #endif

and

    switch (x) {
       case A: ...
       case B: ...
       case C: ...
       default: unreachable(); // should not happen
    }

Flowing off the end of a function is equivalent to a return with no value;
this results in undefined behavior in a value-returning function.
(6.6.3 [stmt.return]).  In my point of view "__builtin_unreachable()"
is just like an undefined behavior - the compiler just assume it won't
happen.

> That at least can lead to better code, and perhaps give more checking or
> optimisation opportunities.

> In between these are things like "assert" and the option of checking
> during development and testing, and disabling checks at later stages.
> 
> A "just return something" solution usually combines the disadvantages of
> all these options.

Agree.  If you really want to return something you should return a
well-defined and documented error code (for example -EINVAL, or you
can define a new constant).
-- 
Xi Ruoyao <xry111@xxxxxxxxxxxxxxxx>
School of Aerospace Science and Technology, Xidian University




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux