C
charlie
I recently came across s function (actually many) whose structure is a
series of nested ifs with the meat of the function at the very centre:
if (condition1)
if (condition2)
if (condition3)
if (condition4)
<Body>
else {
printf("Condition4 failed");
return;
}
else {
printf("Condition3 failed");
return;
}
else {
printf("Condition2 failed");
return;
}
else {
printf("Condition1 failed");
return;
}
To me this is really unreadable and I would re-write as:
if(!condition1) {
printf("Condition 1 failed");
return;
}
....
<Body>
I got to thinking why would you write code this way; seperating the
condition from it's consequences. It occured to me that there may have
been performance related concerns with respect to jumps so with the
original code, in the case of all conditions suceeding, you get no
jumps but with my code you may get as many jumps as there are
conditions because each if block would need to be skipped. I am
certainly not an expert in compilers or machine code and this is
probably a case of premature optimization in either case I just trying
to get into the head of the guy that wrote it in the first place.
Cheers,
Charlie.
series of nested ifs with the meat of the function at the very centre:
if (condition1)
if (condition2)
if (condition3)
if (condition4)
<Body>
else {
printf("Condition4 failed");
return;
}
else {
printf("Condition3 failed");
return;
}
else {
printf("Condition2 failed");
return;
}
else {
printf("Condition1 failed");
return;
}
To me this is really unreadable and I would re-write as:
if(!condition1) {
printf("Condition 1 failed");
return;
}
....
<Body>
I got to thinking why would you write code this way; seperating the
condition from it's consequences. It occured to me that there may have
been performance related concerns with respect to jumps so with the
original code, in the case of all conditions suceeding, you get no
jumps but with my code you may get as many jumps as there are
conditions because each if block would need to be skipped. I am
certainly not an expert in compilers or machine code and this is
probably a case of premature optimization in either case I just trying
to get into the head of the guy that wrote it in the first place.
Cheers,
Charlie.