Sujet : Re: else ladders practice
De : janis_papanagnou+ng (at) *nospam* hotmail.com (Janis Papanagnou)
Groupes : comp.lang.cDate : 31. Oct 2024, 20:24:42
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vg0lhs$2qpi1$1@dont-email.me>
References : 1
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.8.0
On 31.10.2024 13:11, fir wrote:
somethins i got such pices of code like
if(n==1) {/*something/}
if(n==2) {/*something/}
if(n==3) {/*something/}
if(n==4) {/*something/}
if(n==5) {/*something/}
technically i would need to add elses - but the question is if to do that
do teh code has really chance to be slower without else (except some
very prmitive compilers) ??
not adding else makes liek code shorter.. so im not literally sure which
is better
The language (and the compiler) is there to serve me, not vice versa.
While I expect modern compilers to do optimizations you generally
cannot rely on that.
I'm not much interested in doing peep-hole optimizations, that's the
task of the compilers.
There's optimizations on the logic that is of more concern (to me),
and often has even a greater impact on performance.
I use the constructs that serve me best to express what I intend to
implement. (But I have to use what the respective language supports.)
There's (in various languages) different ways to implement cascades;
three way decisions (<0, =0, >0), arrays of switch branches triggered
by a positive integer (1, 2, 3, ...), a case/switch whose argument
is visibly evaluated just once, if-cascades that allow for multiple
possible conditions, and with exclusive conditions. You can also
implement hierarchical cascades considering the assumed distribution
of appearing values (n<3, n>4, ...), or, with unknown distribution,
binary hierarchical nesting of the if-tests. And last but not least,
and depending on what the 'n' is algorithmically bound to, replacing
conditional cascades by OO polymorphism (where possible).
Of course I'd use 'else' to make the intention clear. I'd prefer an
'else-if', if the language supports that, to make things clearer and
the syntax construct simpler and more reliable.
In above example the 'switch' would probably be the obvious way to
write the case (assuming 'n' being an invariant in the if-cascade).
Although the necessity (in "C") for using 'break' makes it clumsy,
I have to admit, but since C is anyway not that abstract as language
I bite the bullet, since that is the most obvious fitting construct
here (as far as no more context is provided).
In a language like Awk you don't need the 'if' and write (e.g.)
n==1 { *something* ; break }
but you might also want to add a 'break' after "something" (as
shown) to explicitly prevent unnecessary further checks. (GNU Awk,
BTW, also supports a more powerful 'switch' that operates not only
on simple scalar data types, but also on strings and patterns.)
Janis