0

ELSE IFs vs nested IF statements

Hmm, I wonder if it's more efficient to use a bunch of ELSE IF statements or rather nested IFs (mainly in higher level programming langs). Did anyone here do any benchmarking? I would be really interested in the results. Thank you in advance for your answers. <3

20th Jan 2022, 10:30 PM
Nogard
Nogard - avatar
7 Respuestas
+ 2
Other languages formally support else if, but C and C++ only recognize it as an else clause with a nested if. Personally, I consider it borderline deceptive to format C/C++ code with apparent else if constructs; however, Brian Kernighan wrote in his book "Elements of Programming Style" that it is acceptable because it can make the code more readable. There is a point where multiple if/else statements might be made more efficient by revamping them into a switch/case statement, which can be faster due to use of a calculated jump instead of multiple test and branch instructions. I will let others address else if for other languages. I would be mildly surprised if there is any difference though.
20th Jan 2022, 11:12 PM
Brian
Brian - avatar
+ 1
They don't give the same result. A if-else if chain does the same as a switch statement. Nested ifs test combinations of conditions.
20th Jan 2022, 11:02 PM
Emerson Prado
Emerson Prado - avatar
0
I'm not talking about a SWITCH, just IF, ELSE IF and ELSE statements. The language doesn't matter.
20th Jan 2022, 10:45 PM
Nogard
Nogard - avatar
0
Brian thanks for this! :)
22nd Jan 2022, 6:25 PM
Nogard
Nogard - avatar
- 1
its called a switch. what language?
20th Jan 2022, 10:36 PM
Slick
Slick - avatar
- 1
That's what you use instead of a long if-elif chain. Again, called a switch. That's what you're describing.
20th Jan 2022, 10:48 PM
Slick
Slick - avatar
- 1
Slick I know, but I asked for the benchmarking... Damn, why did I even bother to write the question.
22nd Jan 2022, 6:21 PM
Nogard
Nogard - avatar