Note following code snippet:
Assume there are only two conditions take in to account and many number of cases
First approach
switch(x)
{
case 1 : if(conditional1) { ... CODE BLOCK 1 ...}; else if(conditional2) {... CODE BLOCK 2 ...}; else {... CODE BLOCK 3 ...}; break; // nested if-else goes here
case 2 : if(conditional1) {/.../}; else if(conditional2) {/.../}; else {/.../}; break;
case X: /... similar pattern follows until default .../ break;
default:break;
};
and Second Approach other-way around
if(conditional1)
{
switch(x)
{
case 1 : /... CODE BLOCK 1 .../ break;
case 2 : /.../ break;
case X: /... similar pattern follows until default .../ break;
default:break;
};
}
else if(conditional2)
{
switch(x)
{
case 1 : /... ... CODE BLOCK 2 .../ break;
case 2 : /.../ break;
case X: /... similar pattern follows until default .../ break;
default:break;
};
}
else
{
switch(x)
{
case 1 : /... ... CODE BLOCK 3 .../ break;
case 2 : /.../ break;
case X: /... similar pattern follows until default .../ break;
default:break;
};
}
- Hope you understand the code pattern
Which approach helps C/C++ compiler to generate better optimized code(obj size and control nodes) ?
If N = Number of Conditional statements , If M = Number of cases ,
If we take N and M parameters in to account,how can we determine which approach is elegant?
Aucun commentaire:
Enregistrer un commentaire