Path: ...!weretis.net!feeder9.news.weretis.net!news.quux.org!eternal-september.org!feeder2.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Dan Purgert Newsgroups: comp.lang.c Subject: Re: else ladders practice Date: Thu, 31 Oct 2024 14:14:49 -0000 (UTC) Organization: A noiseless patient Spider Lines: 68 Message-ID: References: <3deb64c5b0ee344acd9fbaea1002baf7302c1e8f@i2pn2.org> Injection-Date: Thu, 31 Oct 2024 15:14:49 +0100 (CET) Injection-Info: dont-email.me; posting-host="30c0bec475b00646c15587bfe2a34f7f"; logging-data="2862188"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+FNA07lK+Jx0faC0MZgJKkTMP8qxsfPrU=" User-Agent: slrn/1.0.3 (Linux) Cancel-Lock: sha1:W/PjNPKLtNR3Lqm/LnYti1GKyyI= Bytes: 2814 On 2024-10-31, 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) ?? In the above, all conditionals are always checked -- that is the truth of a previous conditional statement has no bearing on subsequent tests. This leads to the potential of tests going off in directions you hadn't necessarily anticipated. However, 'if..elseif..else' will only check subsequent conditionals if the prior statements were false. So for the case that "n=2", you're only ever testing the two cases "if (n==1)" (which is false) and "elseif(n==2)". The computer just skips to the end of the set of statements. Given this MWE (my own terrible code aside ;) ): int main(){ int n=0; printf ("all if, n=%u\n",n); if (n==0) { printf ("n: %u\n",n); n++;} if (n==1) { printf ("n: %u\n",n); n++;} if (n==2) { printf ("n: %u\n",n); n++;} if (n==3) { printf ("n: %u\n",n); n++;} if (n==4) { printf ("n: %u\n",n); n++;} printf ("all if completed, n=%u\n",n); n=3; printf ("with else if, n=%u\n",n); if (n==0) { printf ("n: %u\n",n); n++;} else if (n==1) { printf ("n: %u\n",n); n++;} else if (n==2) { printf ("n: %u\n",n); n++;} else if (n==3) { printf ("n: %u\n",n); n++;} else { printf ("n: %u\n",n); n++;} printf ("with else if completed, n=%u\n",n); } You'll get the output: all if, n=0 n: 0 n: 1 n: 2 n: 3 n: 4 all if completed, n=5 with else if, n=3 n: 3 with else if completed, n=4 HTH :) -- |_|O|_| |_|_|O| Github: https://github.com/dpurgert |O|O|O| PGP: DDAB 23FB 19FA 7D85 1CC1 E067 6D65 70E5 4CE7 2860