Reputation: 21
I've been going through and trying to make sense of C code written for a Z80 micro controller. The coder was self taught and unfortunately the code lacks style and thus readability. Apart from the code being full of goto statements it is also very messy with spacing and alignment all over the place.
I have come to a few IF ELSE statement as follows:
if(value1==1){
code();
}
else
if(value2==1) {
othercode();
}
is this the same as:
1.
if(value1==1){
code();
}
else if(value2==1) {
othercode();
}
or
2.
if(value1==1){
code();
}
if(value2==1) {
othercode();
}
So before I commit to changing all the code I though best to check.
Upvotes: 0
Views: 1710
Reputation: 1575
The first two are same:
else
if(value2==1) {
othercode();
}
is same as:
else if(value2==1) {
othercode();
}
This is different:
if(value1==1){
code();
}
if(value2==1) {
othercode();
}
In the first two cases the control will not go to the else
, in case if
condition is satisfied. But in the last case it will always check both if
statements.
Upvotes: 2
Reputation: 81
if(value1==1){
code();
}
else if(value2==1) {
othercode();
}
this is similar to the code you have given
if(value1==1){
code();
}
else
// this else will check for one statement , now as the next state is if
, so its similar to else if
if(value2==1) {
othercode();
}
Upvotes: 0
Reputation: 6116
Code 1 is exactly the same as original code. You just changed the indentation.
Code 2 will behave differently than original code.
Code 1 means if value1 == 1
is true, execute code()
else check if value2 == 1
is true, then execute othercode()
.
While
Code 2 means if value1 == 1
is true, execute code()
and now check if value2 == 1
is true, then execute othercode()
.
So in a nutshell, in first case else
condition won't be checked if if
block evaluates to true. In second case, both if
s will be checked in all the cases.
Upvotes: 6