How to rewrite complicated lines of C++ code (nested ternary operator)

后端 未结 7 1570
误落风尘
误落风尘 2020-12-05 23:29

I\'ve been looking through someone else\'s code for debugging purposes and found this:

!m_seedsfilter ? good=true : m_seedsfilter==1 ? good=newClusters(Sp) :         


        
相关标签:
7条回答
  • 2020-12-06 00:16

    This is better?

    !m_seedsfilter ? good=true 
                   : m_seedsfilter==1 ? good=newClusters(Sp) 
                                      : good=newSeed(Sp);  
    

    I'll add that, while it's theoretically possible to simplify this expression (by why? It's so much clear!), the resulting expression wouldn't probably be 100% equivalent in all the possible cases... And showing if two expressions are really equivalent in C++ is a problem very very very very very complex...

    The degenerate example I have contrived (http://ideone.com/uLpe0L) (note that it isn't very degenerate... It's only based on a small programming error) is based on considering good a bool, creating two classes UnixDateTime and SmallUnixDateTime, with newClusters() returning a SmallUnixDateTime and newSeed() returning a UnixDateTime. They both should be used to contain a Unix datetime in the format of the number of seconds from 1970-01-01 midnight. SmallUnixDateTime uses an int, while UnixDateTime uses a long long. Both are implicitly convertible to bool (they return if their inner value is != 0, something "classical"), but UnixDateTime is even implicitly convertible to SmallUnixDateTime (this is wrong, because there could be a loss of precision... Here it's the small programming error). On failure of the conversion, a SmallUnixDateTime setted to 0 is returned. In the code of this example there will always be a single conversion: between SmallUnixDateTime to bool or between UnixDateTime to bool...

    While in this similar-but-different example:

    good = !m_seedsfilter ? true 
                          : m_seedsfilter==1 ? newClusters(Sp) 
                                             : newSeed(Sp);
    

    there are two possible paths: SmallUnixDateTime (newClusters(Sp)) is converted to bool or UnixDateTime (newSeed(Sp))is converted first to SmallUnixDateTime and then to bool. Clearly the two expressions aren't equivalent.

    To make it work (or "not work"), newSeed(Sp) returns a value that can't be contained in a SmallUnixTime (std::numeric_limits<int>::max() + 1LL).

    0 讨论(0)
提交回复
热议问题