ECE151 - Lecture 6
ECE151 - Lecture 6
Programming
2
Modular Programming
● Definition includes:
○ return type: data type of the value that function returns to the
part of the program that called it
○ the number of arguments in the call must match the prototype and definition
○ the first argument will be used to initialize the first parameter, the second
argument to initialize the second parameter, etc.
(Program Continues)
Program 6-8 (Continued)
The function call in line 18 passes value1,
value2, and value3 as a arguments to the
function.
Passing Data by Value
● Changes to the parameter in the function do not affect the value of the
argument
Passing Information to Parameters by
Value
● Example: int val=5;
evenOrOdd(val);
val num
5 5
argument in parameter in
calling function evenOrOdd function
● evenOrOdd can change variable num, but it will have no effect on variable
val
Using Functions in
Menu-Driven Programs
● Functions can be used
● A function can return a value back to the statement that called the
function.
● You've already seen the pow function, which returns a value:
double x;
x = pow(2.0, 10.0);
Returning a Value From a Function
Return Type
● The prototype and the definition must indicate the data type of return
value (not void)
○ use it in an expression
Returning a Boolean Value
(Program Continues)
statNum is automatically initialized to
0. Notice that it retains its value between
function calls.
If you do initialize a local static variable, the
initialization only happens once. See Program 6-23.
Default Arguments
(Program Continues)
Program 6-23 (Continued)
Default Arguments
● If not all parameters to a function have default values, the defaultless ones
are declared first in the parameter list:
int getSum(int, int=0, int=0);// OK
int getSum(int, int=0, int); // NO
● When an argument is omitted from a function call, all arguments after it must
also be omitted:
sum = getSum(num1, num2); // OK
sum = getSum(num1, , num3); // NO
Using Reference Variables as Parameters
(Program Continues)
Program 6-25 (Continued)
The & also appears here in the function header.
Reference Variable Notes
Passing a double
(Program Continues)
Passing an int
Program 6-27 (Continued)
The exit() Function
● Example:
exit(0);
● The cstdlib header defines two constants that are commonly passed, to
indicate success or failure:
exit(EXIT_SUCCESS);
exit(EXIT_FAILURE);
Stubs and Drivers
● Useful for testing and debugging program and function logic and design
● Stub: A dummy function used in place of an actual function
○ Usually displays a message indicating it was called. May also display
parameters
● Driver: A function that tests another function by calling it
○ Various arguments are passed and return values are tested
Thank You