samedi 14 août 2021

Will if-else statements nest without brackets?

I want to write something utterly ridiculous that calls for a great depth of conditional nesting. The least disorienting way to write this is to forgo brackets entirely, but I have not been able to find any info on if nesting single-statement if-else guards is legal; the non-nested version causes people enough problems it seems.

Is it valid to write the following? (In both C and C++, please let me know if they differ on this.)

    float x = max(abs(min), abs(max));
    uint32 count = 0u;

    // divides and conquers but, tries to shortcut toward more common values

    if (x < 100'000.f) 
        if (x < 10.f) 
            count = 1u;
        else
            if(x < 1'000.f)
                if (x < 100.f) 
                    count = 2u;
                else
                    count = 3u;
             else 
                if (x < 10'000.f) 
                    count = 4u;
                else
                    count = 5u;
    else 
        ... // covers the IEEE-754 float32 range to ~1.0e+37 (maybe 37 end branches)

--skippable lore--

The underlying puzzle (this is for fun) is that I want to figure out the number of glyphs necessary to display a float's internal representation without rounding/truncation, in constant time. Counting the fractional part's glyph count in constant time was much neater/faster, but unfortunately I wasn't able to figure out any bit-twiddling tricks for the integer part, so I've decided to just brute-force it. Never use math when you can use your fists.

Aucun commentaire:

Enregistrer un commentaire