what is the different between if-else and switch statment
(other than syntax)
Answer Posted / mikew
The switch branches on one value only, whereas the if-else
tests multiple logical expressions.
So you could say that the switch is a subset of if-else.
The potential difference if that switch is conceptually an
N-way branch point, whereas the if-else is always a
(repeated) binary branch.
However, if you are checking, say, a return code, against a
varied list of possibilities, then the switch can give
greater clarity to source code - and allow simpler addition
of new cases, making it easier for maintenance, as well as
allowing the compiler to generate simpler code.
Simpler code is possible because it can generate a jump
table to perform the multiple comparisons, i.e. in pseudo-code:
_jump_table:
DEFW case1_address
DEFW case1_value
...
DEFW caseN_address
DEFW caseN_value
DEFW NULL /* terminator */
- search _jump_table for case_value
- branch to corresponding case_address, or take default
action if NULL terminator found instead.
In the special case that case1 ... caseN values are
sequential numbers (maybe with a few gaps) then the table
and code can be further simplified as a simple indexed branch:
_jump_table:
DEFW case1_address
...
DEFW default_address /* fill in any holes !*/
...
DEFW caseN_address
- check value is between case1_value and caseN_value
- subtract case1_value
- load branch address word from _jump_table word-indexed on
previous result
Is This Answer Correct ? | 27 Yes | 14 No |
Post New Answer View All Answers
Write a program to print factorial of given number using recursion?
What is c system32 taskhostw exe?
GIVEN A FLOATING POINT NUMBER HOW IS IT ACTUALLY STORED IN MEMORY ? CAN ANYONE EXPLAIN?? THE 32 BIT REPRESENTATION OF A FLOATING POINT NUMBER ALLOTS: 1 BIT-SIGN 8 BITS-EXPONENT 23 BITS-MANTISSA
What is struct node in c?
What is the purpose of void pointer?
How can I send mail from within a c program?
If a five digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits.For example if the number that is input is 12391 then the output should be displayed as 23402
All technical questions
What is the general form of #line preprocessor?
How can I handle floating-point exceptions gracefully?
Can you add pointers together? Why would you?
What is integer constants?
What are the main characteristics of c language describe the structure of ac program?
Find the second largest element in an array with minimum no of comparisons and give the minimum no of comparisons needed on an array of size N to do the same.
What are the salient features of c languages?