1
Introduction to “C”Introduction to “C”Control Loops and Control Loops and
Functions Functions Patt and Patel Ch. 13 & 14Patt and Patel Ch. 13 & 14
2
Control StructuresControl StructuresConditionalConditional
– making a decision about which code to execute, based on evaluated expression
– if– if-else– switch
IterationIteration
– executing code multiple times, ending based on evaluated expression
– while– for– do-while
3
““If”If”
if (condition)if (condition) action; action;
condition
action
T
F
Condition is a C expression, which evaluates to TRUE (non-zero) or FALSE (zero).Action is a C statement, which may be simple or compound (a block).
4
Example If StatementsExample If Statements
if (x <= 10)if (x <= 10) y = x * x + 5; y = x * x + 5;
if (x <= 10) {if (x <= 10) { y = x * x + 5; y = x * x + 5; z = (2 * y) / 3; z = (2 * y) / 3;}}
if (x <= 10)if (x <= 10) y = x * x + 5; y = x * x + 5;
z = (2 * y) / 3;z = (2 * y) / 3;
compound statement;both executed if x <= 10
only first statement is conditional; second
statement is always executed
5
More If ExamplesMore If Examplesif (0 <= age && age <= 11)if (0 <= age && age <= 11) kids += 1; kids += 1;
if (month == 4 || month == 6 ||if (month == 4 || month == 6 || month == 9 || month == 11) month == 9 || month == 11) printf(“The month has 30 days.\n”); printf(“The month has 30 days.\n”);
if (x = 2)if (x = 2) y = 5; y = 5;
This is a common programming error (= instead of ==), This is a common programming error (= instead of ==), not caught by compiler because it’s syntactically correct.not caught by compiler because it’s syntactically correct.
always true, so action is always executed!
6
If’s Can Be NestedIf’s Can Be Nestedif (x == 3) if (y != 6) { z = z + 1; w = w + 2; }
if ((x == 3) && (y != 6)) { z = z + 1; w = w + 2;}
is the same as...
7
Generating Code for If StatementGenerating Code for If Statement
; if (x == 2) y = 5;; if (x == 2) y = 5;
LDR R0, R5, #0 LDR R0, R5, #0 ; load x into R0; load x into R0 ADD R0, R0, #-2 ADD R0, R0, #-2 ; subtract 2; subtract 2 BRnp NOT_TRUE BRnp NOT_TRUE ; if non-zero, x is not 2; if non-zero, x is not 2
AND R1, R1, #0 AND R1, R1, #0 ; store 5 to y; store 5 to y ADD R1, R1, #5 ADD R1, R1, #5 STR R1, R5, #-1 STR R1, R5, #-1
NOT_TRUE ... NOT_TRUE ... ; next statement; next statement
8
““If-else”If-else”
if (condition)if (condition) action_if; action_if;elseelse action_else; action_else;
condition
action_if action_else
T F
Else allows choice between two mutually exclusive actions without re-testing condition.
9
Generating Code for If-ElseGenerating Code for If-Else
if (x) {if (x) { y++; y++; z--; z--;}}
else {else { y--; y--; z++; z++;
}}
LDR R0, R5, #0 BRz ELSE ; x is not zero LDR R1, R5, #-1 ; incr y ADD R1, R1, #1 STR R1, R5, #-1 LDR R1, R5, #-2 ; decr z ADD R1, R1, #1 STR R1, R5, #-2 JMP DONE ; skip else code ; x is zeroELSE LDR R1, R5, #-1 ; decr y ADD R1, R1, #-1 STR R1, R5, #-1 LDR R1, R5, #-2 ; incr z ADD R1, R1, #1 STR R1, R5, #-2DONE ... ; next statement
10
Matching Else with IfMatching Else with If
Else is always Else is always associated with associated with closestclosest unassociated if.unassociated if.
if (x != 10) if (y > 3) z = z / 2; else
z = z * 2;
if (x != 10) { if (y > 3) z = z / 2; else z = z * 2;
}
is the same as...
if (x != 10) { if (y > 3) z = z / 2;
}else z = z * 2;
is NOT the same as...
11
Chaining If’s and Else’sChaining If’s and Else’s
if (month == 4 || month == 6 || month == 9 || if (month == 4 || month == 6 || month == 9 || month == 11) month == 11) printf(“Month has 30 days.\n”); printf(“Month has 30 days.\n”);else if (month == 1 || month == 3 ||else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 5 || month == 7 || month == 8 || month == 10 || month == 8 || month == 10 || month == 12) month == 12) printf(“Month has 31 days.\n”); printf(“Month has 31 days.\n”);
else if (month == 2)else if (month == 2)
printf(“Month has 28 or 29 days.\n”);printf(“Month has 28 or 29 days.\n”);
elseelse
printf(“Don’t know that month.\n”);printf(“Don’t know that month.\n”);
12
““While”While”
while (test)while (test) loop_body; loop_body;
test
loop_body
T
F
Executes loop body as long as test evaluates to TRUE (non-zero).
Note: Test is evaluated before executing loop body.
13
Generating Code for WhileGenerating Code for While
x = 0;while (x < 10) { printf(“%d ”, x); x = x + 1;}
AND R0, R0, #0 STR R0, R5, #0 ; x = 0 ; testLOOP LDR R0, R5, #0 ; load x ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R5, #0 ; load x ... <printf> ... ADD R0, R0, #1 ; incr x STR R0, R5, #0 JMP LOOP ; test again
DONE ; next statement
14
Infinite LoopsInfinite LoopsThe following loop will never terminate:The following loop will never terminate:
x = 0;x = 0;while (x < 10)while (x < 10) printf(“%d ”, x); printf(“%d ”, x);
Loop body does not change condition, so test Loop body does not change condition, so test never fails.never fails.
This is a common programming error that can be This is a common programming error that can be difficult to find.difficult to find.
15
““For”For”
for (init; end-test; re-init)for (init; end-test; re-init) statement statement
init
test
loop_body
re-init
F
T
Executes loop body as long as test evaluates to TRUE (non-zero).Initialization and re-initialization code includedin loop statement.
Note: Test is evaluated before executing loop body.
16
Generating Code for ForGenerating Code for For
for (i = 0; i < 10; i++) printf(“%d ”, i);
; init AND R0, R0, #0 STR R0, R5, #0 ; i = 0 ; testLOOP LDR R0, R5, #0 ; load i ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R5, #0 ; load i ... <printf> ... ; re-init ADD R0, R0, #1 ; incr i STR R0, R5, #0 JMP LOOP ; test again
DONE ; next statement
This is the sameas the while example!
17
Example For LoopsExample For Loops/* -- what is the output of this loop? -- *//* -- what is the output of this loop? -- */
for (i = 0; i <= 10; i ++)for (i = 0; i <= 10; i ++) printf("%d ", i); printf("%d ", i);
/* -- what does this one output? -- *//* -- what does this one output? -- */
letter = 'a';letter = 'a';
for (c = 0; c < 26; c++)for (c = 0; c < 26; c++) printf("%c ", letter+c); printf("%c ", letter+c);
/* -- what does this loop do? -- *//* -- what does this loop do? -- */
numberOfOnes = 0;numberOfOnes = 0;for (bitNum = 0; bitNum < 16; bitNum++) {for (bitNum = 0; bitNum < 16; bitNum++) { if (inputValue & (1 << bitNum)) if (inputValue & (1 << bitNum)) numberOfOnes++; numberOfOnes++;}}
18
Nested LoopsNested Loops
Loop body can (of course) be another loop.Loop body can (of course) be another loop.
/* print a multiplication table *//* print a multiplication table */
for (mp1 = 0; mp1 < 10; mp1++) {for (mp1 = 0; mp1 < 10; mp1++) { for (mp2 = 0; mp2 < 10; mp2++) { for (mp2 = 0; mp2 < 10; mp2++) { printf(“%d\t”, mp1*mp2); printf(“%d\t”, mp1*mp2); } } printf(“\n”); printf(“\n”);
}}
Braces aren’t necessary, but they make the code easier to read.
19
Another Nested LoopAnother Nested Loop
The test for the inner loop depends on the The test for the inner loop depends on the counter variable of the outer loop.counter variable of the outer loop.
for (outer = 1; outer <= input; outer++) for (outer = 1; outer <= input; outer++) {{ for (inner = 0; for (inner = 0; inner < outerinner < outer; inner++); inner++) { { sum += inner; sum += inner; } }}}
20
For vs. WhileFor vs. WhileIn general:In general:
ForFor loop is preferred for loop is preferred for countercounter-based loops.-based loops.
– Explicit counter variable– Easy to see how counter is modified each loop
WhileWhile loop is preferred for loop is preferred for sentinelsentinel-based loops.-based loops.
– Test checks for sentinel value.
Either kind of loop can be expressed as the other,Either kind of loop can be expressed as the other,so it’s really a matter of style and readability.so it’s really a matter of style and readability.
21
““Do-While”Do-While”
dodo loop_body; loop_body;
while (test);while (test);
loop_body
testT
FExecutes loop body as long as test evaluates to TRUE (non-zero).
Note: Test is evaluated after executing loop body.
22
““Switch”Switch”
switch (expression) {switch (expression) {case const1:case const1: action1; break; action1; break;case const2:case const2: action2; break; action2; break;default:default: action3; action3;
}}
evaluateexpression
= const1?
= const2?
action1
action2
action3
T
T
F
F
Alternative to long if-else chain. If break is not used, then case "falls through" to the next.
23
Switch ExampleSwitch Example/* same as month example for if-else *//* same as month example for if-else */
switch (month) {switch (month) { case 4: case 4: case 6: case 6: case 9: case 9: case 11: case 11: printf(“Month has 30 days.\n”); printf(“Month has 30 days.\n”); break; break; case 1: case 1: case 3: case 3: /* some cases omitted for brevity...*/ /* some cases omitted for brevity...*/ printf(“Month has 31 days.\n”); printf(“Month has 31 days.\n”); break; break;
case 2:case 2: printf(“Month has 28 or 29 days.\n”); printf(“Month has 28 or 29 days.\n”); break; break; default: default: printf(“Don’t know that month.\n”); printf(“Don’t know that month.\n”);
}}
24
More About SwitchMore About Switch
Case expressions must be constant.Case expressions must be constant.
case i:case i: /* illegal if i is a variable *//* illegal if i is a variable */
If no break, then next case is also executed.If no break, then next case is also executed.
switch (a) {switch (a) { case 1: case 1: printf(“A”); printf(“A”); case 2: case 2: printf(“B”); printf(“B”); default: default: printf(“C”); printf(“C”); } }
If a is 1, prints “ABC”.If a is 2, prints “BC”.
Otherwise, prints “C”.
25
FunctionFunctionSmaller, simpler, subcomponent of programSmaller, simpler, subcomponent of programProvides abstractionProvides abstraction
– hide low-level details– give high-level structure to program, easier to understand
overall program flow– enables separable, independent development
C functionsC functions
– zero or multiple arguments passed in– single result returned (optional)– return value is always a particular type
In other languages, called procedures, subroutines, ...In other languages, called procedures, subroutines, ...
26
Example of High-Level Example of High-Level StructureStructure
main()main(){{ SetupBoard(); SetupBoard(); /* place pieces on board *//* place pieces on board */
DetermineSides(); DetermineSides(); /* choose black/white *//* choose black/white */
/* Play game *//* Play game */ do { do { WhitesTurn(); WhitesTurn(); BlacksTurn(); BlacksTurn(); } while (NoOutcomeYet()); } while (NoOutcomeYet());}}
Structure of programis evident, even withoutknowing implementation.
27
Functions in CFunctions in CDeclarationDeclaration (also called prototype) (also called prototype)
int Factorial(int n);int Factorial(int n);
Function callFunction call -- used in expression -- used in expression
a = x + Factorial(f + g);a = x + Factorial(f + g);
type ofreturn value
name offunction
types of allarguments
1. evaluate arguments
2. execute function
3. use return value in expression
28
Function DefinitionFunction DefinitionState type, name, types of argumentsState type, name, types of arguments
– must match function declaration– give name to each argument (doesn't have to
match declaration)
int Factorial(int n)int Factorial(int n)
{{
int i;int i; int result = 1; int result = 1; for (i = 1; i <= n; i++) for (i = 1; i <= n; i++) result *= i; result *= i; return result; return result;
}}
gives control back tocalling function and
returns value
29
Why Declaration?Why Declaration?
Since function definition also includes return and Since function definition also includes return and argument types, why is declaration needed?argument types, why is declaration needed?
Use might be seen before definition.Use might be seen before definition.Compiler needs to know return and arg types and number of Compiler needs to know return and arg types and number of arguments.arguments.
Definition might be in a different file, written by a Definition might be in a different file, written by a different programmer.different programmer.
– include a "header" file with function declarations only– compile separately, link together to make executable
30
ExampleExampledouble ValueInDollars(double amount, double rate);double ValueInDollars(double amount, double rate);
main()main(){{ ... ... dollars = ValueInDollars(francs, dollars = ValueInDollars(francs, DOLLARS_PER_FRANC); DOLLARS_PER_FRANC); printf("%f francs equals %f dollars.\n", printf("%f francs equals %f dollars.\n", francs, dollars); francs, dollars); ... ...
}}
double ValueInDollars(double amount, double rate)double ValueInDollars(double amount, double rate)
{{
return amount * rate;return amount * rate;
}}
declaration
function call (invocation)
definition
31
Implementing Functions: Implementing Functions: OverviewOverview
Activation recordActivation record
– information about each function, including arguments and local variables
– stored on run-time stackCalling function
push new activation recordcopy values into argumentscall function
get result from stack
Called function
execute codeput result in activation recordpop activation record from stackreturn
32
Run-Time StackRun-Time StackRecall that local variables are stored on the run-Recall that local variables are stored on the run-time stack in an time stack in an activation recordactivation record
Frame pointer (R5)Frame pointer (R5) points to the beginning of a points to the beginning of a region of activation record that stores local region of activation record that stores local variables for the current functionvariables for the current function
When a new function is When a new function is calledcalled, its activation record , its activation record is is pushedpushed on the stack; on the stack;
when it when it returnsreturns, its activation record is , its activation record is popped popped off off of the stack.of the stack.
33
Run-Time StackRun-Time Stack
main
Memory
R6
Watt
Memory
R6
main
Memory
main
Before call During call After call
R5
R5
R6R5
34
Activation RecordActivation Record
int NoName(int a, int b)int NoName(int a, int b){{ int w, x, y; int w, x, y; . . . . . . return y; return y;}}
Name Type Offset Scope
abwxy
intintintintint
450-1-2
NoNameNoNameNoNameNoNameNoName
yxw
dynamic linkreturn addressreturn value
ab
bookkeeping
locals
args
R5
35
Activation Record Activation Record BookkeepingBookkeeping
Return valueReturn value
– space for value returned by function– allocated even if function does not return a value
Return addressReturn address
– save pointer to next instruction in calling function– convenient location to store R7 in case another function
(JSR) is called
Dynamic linkDynamic link
– caller’s frame pointer– used to pop this activation record from stack
36
Example Function CallExample Function Callint Volta(int q, int r) int Volta(int q, int r) {{ int k; int k; int m; int m; ... ... return k; return k;}}
int Watt(int a)int Watt(int a){{ int w; int w; ... ... w = Volta(w,10); w = Volta(w,10); ... ... return w; return w;}}
37
Calling the FunctionCalling the Functionw = Volta(w, 10);w = Volta(w, 10);
; push second arg; push second argAND R0, R0, #0AND R0, R0, #0ADD R0, R0, #10ADD R0, R0, #10ADD R6, R6, #-1ADD R6, R6, #-1STR R0, R6, #0STR R0, R6, #0; push first argument; push first argumentLDR R0, R5, #0LDR R0, R5, #0ADD R6, R6, #-1ADD R6, R6, #-1STR R0, R6, #0STR R0, R6, #0
; call subroutine; call subroutineJSR VoltaJSR Volta
qrwdyn linkret addrret vala
25 1025
xFD00
new R6
Note: Caller needs to know number and type of arguments, doesn't know about local variables.
R5
R6
38
ANSI C SummaryANSI C Summary
• C is the basis for most modern C is the basis for most modern languages: Java, C#, C++languages: Java, C#, C++
• Has a fairly close relationship to the Has a fairly close relationship to the hardware, not too much abstractionhardware, not too much abstraction
• For the most part it is portable For the most part it is portable across plateformsacross plateforms
• Use “gcc” or “cc” on UNIX machineUse “gcc” or “cc” on UNIX machine
39
Questions?Questions?
40