Sujet : Re: else ladders practice
De : bc (at) *nospam* freeuk.com (Bart)
Groupes : comp.lang.cDate : 31. Oct 2024, 22:33:40
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vg0t3j$2ruor$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
On 31/10/2024 12: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
There are several clear patterns here: you're testing the same variable 'n' against several mutually exclusive alternatives, which also happen to be consecutive values.
C is short of ways to express this, if you want to keep those 'somethings' as inline code (otherwise arrays of function pointers or even label pointers could be used).
The closest way is to use 'switch', which is also likely to do all comparisons at the same time (in O(1) time), if the compiler thinks that's the best way to do it.
The next closest is to use an if-else chain, which is almost what you have. But apparently you don't like writing 'else if' instead of 'if':
if(n==1) {/*something1*/}
else if(n==2) {/*something2*/}
else if(n==3) {/*something3*/}
else if(n==4) {/*something4*/}
else if(n==5) {/*something5*/}
This is actually cleaner than the 'break' you have to use with switch.
It also guarantees, whatever the compiler, that you don't waste time doing the rest of the rests.