270 - 2 - C Functions - Pepper
270 - 2 - C Functions - Pepper
270 - 2 - C Functions - Pepper
Pepper
Objectives
• Create functions
• Function prototypes
• Parameters
– Pass by value or reference
– Sending a reference
• Return values
• Math functions
Intro
• Why:
– Divide and conquer
– Reuse abstractions
• What:
– Used prepackaged functions
• printf, scanf, rand()
– Create our own
– Pass parameters
– Accept return values
Math
• #include <math.h>
• Use any math function
• If c1 = 13.0, d = 3.0 and f = 4.0, then the
statement
printf( "%.2f", sqrt( c1 + d * f ) );
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
•
Create
Choose a name
your function
– Function should perform a single well defined task
– If you can’t find a concise descriptive name, you may have too
many jobs for the function
• Define a contract
– Inputs
• Arguments – choose type
• None should be noted as void
• Will the function change the parameter’s value?
– Output
• Only one ; by convention, 0 means good
• Write prototype
– Looks like function header but has ;
– int square( int y );
– Tells compiler what is valid input and output
– Forces type conversion
• Write body
• Call the function
Sample Function
#include <stdio.h>
Any data
number 4.0 y intended for y
in the
function goes
to the
location of
number in the
main
program
When to Use Value and Reference
Parameters
• We use value parameters when:
– We are not going to change the parameters’ value
– We may change it but the main program should
not know about it
• When we are simply printing the value
– We use reference parameters when:
– We are going to change the parameter’s value and
the main program MUST know about it.
– We are reading in a new value
Recursion – Function calls itself
• Method for repetition
• Need a stopping condition
• Need to call with some way to reach the stop
eventually
• Pushes copies of itself onto the stack (memory
use)
Summary
• Create a function
– <return type> <function name> (<type> <var> …)
• Call a function (can call it recursively)
– <function name> (<var>…)
• Pass by reference
– Argument accepts address: *<var name>
– Caller sends address: &<var name>
• Variable life
– Local vs global