IT11a - Programming Notes
IT11a - Programming Notes
Functions
Structured Programming
- Keep decomposing (also known as factoring) a problem into smaller problems until you have
a collection of small problems that you can easily solve.
- Each function solves one of the small problems obtained using top-down design.
#include <stdio.h>
declarations
statements
Some Terminology
● When a return statement is executed, program control is immediately passed back to the
calling environment.
• If an expression follows the keyword return, the value of the expression is returned to the
calling environment as well.
return;
return expression;
If There is No return
● Control is passed back to the calling environment when the closing brace of the body is
encountered.
or
exit(expr);
operating system.
● In functions other than main(), the effects of return and exit are different.
● exit(expr) always causes the program to terminate and returns an exit status to the operating
system. The value in expr is the exit status.
int main(void) {
int j, k, m;
m = min(j, k);
if (a < b)
return a;
else
return b;
Function Prototypes
● A function prototype tells the compiler:
• The number and type of arguments that are to be passed to the function.
double sqrt(double);
● The parameter list is typically a comma-separated list of types. Identifiers are optional.
is equivalent to
Function Invocation
● As we have seen, a function is invoked (or called) by writing its name and an appropriate list
of arguments within parentheses.
• The arguments must match in number and type the parameters in the parameter list of the
function definition.
Call-by-Value
● In C, all arguments are passed call-by-value.
• This means that each argument is evaluated, and its value is used in place of the
corresponding formal parameter in the called function.
int main(void)
int n = 3, sum;
printf(“%d\n”, n);
sum = compute_sum(n);
printf(“%d\n”, n);
printf(“%d\n”, sum);
return 0;
int compute_sum(int n)
int sum = 0;
/* 3 is printed */
/* 3 is printed */
sum += n;
return sum; }
int main(void)
. ..
. ..
. ..
void prn_random_numbers(int k)
. ..
. ..
. ..
void prn_random_numbers(int k)
. ..
int main(void)
. ..
• A common error for beginners is assuming the the value in v can be changed by a function
call such as f(v).
Style
● Avoid naming functions you write with the same name as system functions.