01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Conditional statements<br />

301<br />

based on the value of variables or actions of the user and change their behavior or<br />

flow of execution to suit.<br />

Making conditional decisions is a fundamental part of any programming language,<br />

and C is no different.<br />

B.3.1<br />

The if-else statement<br />

The if-else statement is the simplest of the conditional statements. It evaluates a single<br />

Boolean expression and executes one set of statements if it evaluates to true and<br />

another set of statements if it evaluates to false. The general form is as follows:<br />

if (condition) {<br />

statement block 1<br />

} else {<br />

statement block 2<br />

}<br />

The condition can be any Boolean expression. If the expression evaluates to true<br />

(any value other than zero), statement block 1 is executed; otherwise, statement block<br />

2 is executed. No matter which path is selected, execution then proceeds to the first<br />

statement immediately after the if statement.<br />

The following if statement checks to see if the value of variable x holds a value<br />

greater than 10 and prints a different result depending on the result of this comparison.<br />

int x = 45;<br />

if (x > 10) {<br />

NSLog(@"x is greater than 10");<br />

} else {<br />

NSLog(@"x is less than or equal to 10.");<br />

}<br />

The else keyword and associated statement block are optional and don’t need to be<br />

included if you have no statements you wish to execute whenever the specified condition<br />

evaluates to false. The following if statement prints a message only if variable x<br />

is greater than 10.<br />

int x = 45;<br />

if (x > 10) {<br />

NSLog(@"x is greater than 10");<br />

}<br />

In this case where only one statement is required to be executed in a statement<br />

block, it’s not necessary to wrap the statement in curly braces. The semicolon at the<br />

end of the statement is still required, though, because C uses the semicolon to terminate<br />

the current statement rather than a separator between multiple statements, as<br />

in some other languages. The following if statement is identical in function to the<br />

previous one:<br />

int x = 45;<br />

if (x > 10)<br />

NSLog(@"x is greater than 10");

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!