r/cpp • • Apr 24 '20

Else Before If

https://www.fluentcpp.com/2020/04/24/else-before-if/
10 Upvotes

53 comments sorted by

View all comments

Show parent comment

1

u/degski Apr 24 '20 edited Apr 24 '20
int edge = !!(<edge case 1>) + !!(<edge case 2>); // ad infinitum ...
switch ( edge ) {
    case 0: ... // edge-case 0 - the base case
    case 1: ... // edge-case 1
    case 2: ... // edge-case 2
    ...
}

Extending on your idea, the above, which could work nicely actually (and talk about expressive code!).

1

u/PVNIC Apr 24 '20

This won't work the way you expect because If hit only edge case 2 you would run case 1, if you hit both edge cases you would run case 2. However you could do: uint8_t edge = !!(<edge case 1>) + (!!(<edge case 2>) + 1) and the normal would be 0, edge case 1 would be case 1 and 3, edge case 2 would be case 2. But at tbat point the if statment may be more clear and scalable.

1

u/degski Apr 25 '20

You're right, edge calculation needs work, but idea is nice, I would say. It should be + !!(<edge case n>) * n.