What is a function?:
- a function is a group of code that takes in some arguments (inputs) and returns a value (output)
Why is a function important?:
- you can reuse code
- you can reuse the code inside the function
- you can reuse functions
- you can update a function and everywhere that calls the function will get the updated code
- you can give a group of code a name to express what the group of code is trying to do
- using functions with expressive names makes your code easier to read than using comments
When is a good time to utilize functions?:
- whenever you find yourself copy and pasting code
- whenever you find yourself wanting to add a comment to explain what a section of code is doing
- comments are notes to yourself and other programmers within the code
- like Post-It notes on a word document
- example usage:
// single line comment
-
/* multi-line comment: line 1 multi-line comment: line2 */
How to utilize functions?:
- define a function
your_function
is the function namedouble your_function
tells the compiler that the function is going to return a value with typedouble
your_function (int first_argument, double second_argument)
is the argument list; the list of arguments (and the type of each argument) that the functions expects as inputs
- call a function
your_function(first_argument, second_argument)
is calls the functionyour_function(first_argument, second_argument)
are the arguments passed to the function
- function prototype:
- a function can be declared first with a function prototype, called, and then defined
- when building a program using multiple .c files, function prototypes will make your life easier (and the program might not compile without it)
- the function prototype tells compiler the name of the function (e.g.
your_function
, the inputs of the function (arguments and argument type, e.g.int first_argument
&double second_argument
), and the output of the function (the type of the value, e.g.double your_function
)
- arguments are values or variables that is passed to the function
- read more at http://www.mycplus.com/tutorials/c-programming-tutorials/functions/
- read more at http://en.wikibooks.org/wiki/C_Programming/Procedures_and_functions; it's a long read but contains a lot of useful information
- read more at http://www.tutorialspoint.com/ansi_c/c_using_functions.htm; it's a long read but contains a lot of useful information