-
regarding if statements
Code:
while( foo ){
if( condition 1 )
do something;
if( condition 2 )
do something else;
if( condition 3 )
do something else again;
}
So my question is about how I used my if statements. Is that a proper way to write code?
It may seem like a dumb question, but I would like an opinion.
~/kermit
-
I think what I am asking is what is the difference between what I posted here and using if / else if statements
-
It depends on what you want your code to do.
Here's what I think you may have meant:
Code:
while( foo )
{
if( condition 1 )
{
do something for cond 1;
}
else if( condition 2 )
{
do something for cond 2;
}
else if( condition 3 )
{
do something for cond 3;
}
else
{
do something if all the above were false
}
}
-
Yes, I meant what you have written there. The thing I was wondering about was if it is proper to leave the else part off the if, so instead of
Code:
if( condition 1 )
{
do something for cond 1;
}
else if( condition 2 )
{
do something for cond 2;
}
else if( condition ...
and so on (as you wrote), you would have,
Code:
if( condition 1 )
{
do something for cond 1;
}
if( condition 2 )
{
do something for cond 2;
}
if( condition...
where the else is omitted.
The only reason I ask is that I have seen this sort of thing in various places online, yet in my C books, I only see what you wrote with 'else if' - I assume that it is proper to write the way you demonstrated, but the other way is somewhat 'legal'?
-
Both ways are legal... but if condition1 and condition2 are both true, your code will execute the code for both, while the other code will only execute the code for condition1
-
Ah, so it would be good to make sure that multiple conditions could not be true then when deciding which way to code.