Reputation: 112
My question:
Is this:
if (...) {
} else if (...) {
}
Equal to this?
if (...) {
} else {
if (...) {
}
}
Indeed, I guess that in the two cases the result would be the same but is else..if a different statement in C ?
Upvotes: 3
Views: 190
Reputation: 13
If you write
if(...){
} else{
if(...){ ... }
}
That would be the same as
if (...) {
} else if (...) {
}
As long as you keep the else
statement empty except for the second if statement.
else if
isn't technically its own statement. else if is literally an else statement and then an if statement.
Upvotes: 0
Reputation: 222526
They are almost the same thing.
They are the same as a compiler would treat them exactly as they stand now.
However, they are not the same for development purposes. If additional code is inserted immediately after the end of the enclosed if
statement, it will be grouped with that statement in the code with the braces around that if
statement but not in the code without those braces. Issues like this are potential causes of bugs, so the difference may be significant.
Upvotes: 0
Reputation: 14876
To address the comments suggesting drawing truth table, logically equivalent programs aren't always the same in terms of the generated assembly (they will behave the same) but consider:
int main()
{
int a = 1;
if (a)
if(a)
return 0;
}
And
int main()
{
int a = 1;
if(a)
return 0;
}
Compiling with no optimization -O0
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 1
cmp DWORD PTR [rbp-4], 0
je .L2
cmp DWORD PTR [rbp-4], 0
je .L2
mov eax, 0
jmp .L3
.L2:
mov eax, 0
.L3:
pop rbp
ret
main:
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 1
cmp DWORD PTR [rbp-4], 0
je .L2
mov eax, 0
jmp .L3
.L2:
mov eax, 0
.L3:
pop rbp
ret
Upvotes: 0
Reputation: 213711
The C language has no feature called else if
. That one is only obtained through coding style. Your example is 100% equivalent to this:
if (...) {
}
else
if (...) {
}
Where the second if
is a single statement below else
, so we can write it without {}
.
Upvotes: 2
Reputation: 12732
if (...) {
} else if (...) {
}
is same as
if (...) {
} else {
if (...) {
}
}
but
if (...) {
} else if (...) {
}
is not same as
if (...) {
} else {
... // extra statements
if (...) {
}
}
Upvotes: 2