Let me explain a bit more from today's class.
main is a function, just like that tax function that I wrote in class.
The compiler knows to call (start) main when your program begins. In
main, you can call other functions. Such as scanf, printf, etc, from the
stdio.h library, or math.h, or whatever library file you include in your
program. These are external functions. You can define your own
functions, internally or externally, to your program.
In class, tax was defined (written) inside my program code file. When
this was done, I needed to set the header definitions to the compiler,
so it knows what parameters (variables) my function will work with, as
well as what value type it will return (if any).
When the program runs, and it reaches a function, it will branch off and
go to (call) the function and run it's lines of code. When the function
returns, it goes back to the place in the program where the function was
called. If there is a value turned, it can be assigned a the variable.
Such as:
double price;
price=tax(10);
This will assign the return value of tax to price. In this case, tax
will work on the value of 10 and compute whatever it should for tax of
10. tax will then return a value and the compiler assigns this to the
variable price.
Modular
Function call
Parameters
-
Real (Actual) Parameter - Argument to the function
-
Dummy (Formal) parameter - variable inside the function
Variables are passed the a function by VALUE.
Header for a function is part of the function definition.
/* function header. */
int addthem(int a, int b)
{
return a+b;
}
Prototype for a function - also called the function declaration:
int addthem(int a, int b);
Headers (.h) and prototypes.
If statements with multiple returns via if statements.
Multiple parameters.
Loop in a function.
Separate compilation of files.
Driver program to test the function.
void functions and return
void functions and void parameters
void testing(void)
Functions that have no parameters but have a return value.
Important Ideas of Functions. Useful when creating comments for a function:
-
Input - things received from the outside world
-
Process - accomplishments of the function
-
Output - results from the function to the outside world
Return value from print (# of characters printed)& scanf (# of successful
characters read in).
Changing values in a function via pointers:
void change(int *num, int i) {
*num=i;
}
int a=5;
change(&a,10);