C programming notes - School of Physics
C programming notes - School of Physics
C programming notes - School of Physics
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
C <strong>programming</strong> <strong>notes</strong><br />
file:///F:/my_docs/web_phys2020/C<strong>programming</strong><strong>notes</strong>.html<br />
23 <strong>of</strong> 40 19/03/2007 10:06 AM<br />
else /* NOTE: possible ambiguity here, the compiler uses */<br />
y = 3; /* the closest if statement that does not have */<br />
else { /* an else clause */<br />
x = 4;<br />
y = 5;<br />
}<br />
Example Program ifelse.c<br />
Break and continue<br />
These two statements are used in loop control.<br />
"break" exits the innermost current loop.<br />
"continue" starts the next iteration <strong>of</strong> the loop.<br />
Here is an examaple program with break and continue (breakcon.c)<br />
Infinite loops<br />
Here are three ways <strong>of</strong> writing an infinite loop, choose whichever one you like:<br />
for (;;;) {<br />
statement;<br />
}<br />
while (1) {<br />
statement;<br />
}<br />
do {<br />
statement;<br />
} while (1);<br />
Infinite loops can be useful. They are normally terminated using a conditional test with a "break" or "return" statement.<br />
For example:<br />
while (1) {<br />
statement;<br />
if (logical_condition) break;<br />
}<br />
goto<br />
C does have a "goto" statement, but you normally don't need it. Using "goto" is usually a result <strong>of</strong> bad <strong>programming</strong><br />
(although in some circumstances it can be a sensible choice).<br />
The switch statement<br />
The switch statement allows you to choose between multiple paths <strong>of</strong> execution depending on the value <strong>of</strong> an<br />
expression. It could be replaced by a series <strong>of</strong> if statements, but switch can make the flow <strong>of</strong> the program easier to<br />
understand.<br />
switch (expression) {<br />
case const-expression: statements<br />
case const-expression: statements<br />
default: statements<br />
}<br />
Beware that control will flow from one case to the next unless you explicitly include a break statement to cause control<br />
to skip to the end <strong>of</strong> the switch statement.<br />
Here is an example <strong>of</strong> using switch:<br />
switch (i) {<br />
case 0: printf("i had the value zero\n");<br />
break;<br />
case 1:<br />
case 2: printf("i was either one or two\n");