Professional Documents
Culture Documents
Software Development
Nigel Davies and Adrian Friday
First test in the lab
** next week **
We have been
encouraging you to
divide problems up into
smaller steps
Decomposing problems
• We solve pretty much all problems by
repeatedly decomposing it into a series
of smaller steps until the problem is
tractable.
refinement
Decomposing problems
• Most programming languages give us
some support for this:
• C lets us define functions which
package and name specific functionality
• And libraries – sets of pre-compiled
functions we can call from our
programs
Functions
• Help us avoid repetition by ‘factoring out’ common elements
we can ‘reuse’
• Create ‘reusable units’ of code (we can package into libraries
others can use)
• Separate out well defined tasks into logical reusable blocks,
improving readability and maintenance
• Examples include:
• getting user input (scanf)
• printing to the screen (printf)
• comparing two strings
In C
Function definitions have the form:
•direct-declarator ( parameter-
type-list )
• parameter-type-list could be empty (no
parameters)
• A function may return a simple arithmetic type
(e.g. an int), but not arrays or other functions
• They are followed by a compound-statement,
i.e. {…}, the function body, as with main()
Program flow
Functions change the order of execution
Functions change the ‘flow’
get_user_input
display_some_
output
main
❷ int timesbytwo(int number)
{
return number * 2;
}
❶ int main()
{
int value = 4, result;
result ❸
= timesbytwo(value);
printf("Twice value is %d\n", result);
}
A function call in more detail
This is the
type that is
returned
int timesbytwo(int number) this is the
{
return number * 2; formal
}
argument
int main()
Note! { (note the
int value = 4, result;
result = timesbytwo(value); ‘int’)
printf("Twice value is %d\n", result);
}
void sayhello(void)
{
int main()
printf("hello.\n");
{
} sayhello();
}
int main()
{
int x = 0;
changescorebyone(x); x 0
printf("x = %d\n", x);
}
x=0
void changescorebyone(int score)
0
{
1
score++;
}
int main()
{
int score = 0; 0
changescorebyone(score);
printf("%d\n", score);
}
i.e. the parameter
values in the function
are only ever a copy
(pass by value)!
Nothing links the variables inside the function scope,
including the parameters, with those outside
And now for some
work for you :)
You and the person
next to you need to
build a calculator
One person writes the
functions, one person
writes the main
program that calls the
functions
You need functions to
add, subtract, multiply
and divide numbers
go :)
Review of caller/ callee
solutions
Important gotchas
Where to declare
// Prototype for changescorebyone
int main()
declared before you call them {
int score = 0;
• Or, a ‘function prototype’, // Function call
changescorebyone(score);
needs to appear before you }
printf("%d\n", score);
call it
// Declaration, note types must match