Thursday, April 21, 2011

Conditional Statements - if-else statement and ? operator

Conditional statements execute a block or set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in curly brackets. For example:
if (value>5) {x=7;}
Note: If the block (ie. curly brackets) contains only one statement, you may leave the brackets off. But this is not good programming practice. The curly brackets make the code more consistent and easier to read.
Occasionally you may want to perform some actions for the false outcome of a condition as well. The else keyword is used to separate branches.
if (name=="Fred") {x=4;}
else {x=20;};
Note: When the conditional if statement is used only to make an assignment to one variable, you can use the terse C conditional operator. A simple example is:
x=(name=="Fred") ? 4 : 20;

See here for conditional operator.

No comments:

Post a Comment