Lecture 8: Continued Functions
Wednesday, February 22, 2012[Up] [Previous Lecture] [Next Lecture]
Reading Assigned: None
Homework Due: Homework 03
Homework Assigned: Homework 04
Classwork Assigned: Classwork 05
Topics Covered:
- Reminder about using script
- Feedback on course
- Homework 3 review - questions
- Classwork 5 - Functions
- Functions
- Arguments
- Return value
- Variables inside functions
- Forward declarations
- Example of incorrect ordering of functions
- Result of trying to compile:
linux1[23]% gcc -Wall func_order_bad.c -o func_order_bad func_order_bad.c: In function ‘main’: func_order_bad.c:12: warning: implicit declaration of function ‘func1’ func_order_bad.c:13: warning: implicit declaration of function ‘func2’ func_order_bad.c: At top level: func_order_bad.c:17: warning: conflicting types for ‘func1’ func_order_bad.c:12: note: previous implicit declaration of ‘func1’ was here func_order_bad.c:22: warning: conflicting types for ‘func2’ func_order_bad.c:13: note: previous implicit declaration of ‘func2’ was here
- Example of correct ordering of functions
- Result of trying to compile:
linux1[26]% gcc -Wall func_order_good.c -o func_order_good linux1[27]% ./func_order_good Function 1 called Function 2 called
- Example of function forward declaration
linux1[30]% gcc -Wall func_forward_dec.c -o func_forward_dec linux1[31]% ./func_forward_dec Function 1 called Function 2 called
- Declaration - tells compiler the return value, name, and arguments
- Definition - tells compiler the implementation of a declared function
- Declaration and definition can (and often do) occur at the same time, but don't need to
- BUT -- if they occur at different points, the function signature must match
- Example of function declarations that don't match
linux1[38]% gcc -Wall func_forward_dec_bad.c -o func_forward_dec_bad func_forward_dec_bad.c:33: error: conflicting types for ‘func1’ func_forward_dec_bad.c:15: note: previous declaration of ‘func1’ was here func_forward_dec_bad.c:38: error: conflicting types for ‘func2’ func_forward_dec_bad.c:16: note: previous declaration of ‘func2’ was here
- Function signature - the set of return value, name, and argument types
- A more complex function example
linux1[69]% gcc -Wall func_complex.c -o func_complex linux1[70]% ./func_complex func2 was passed arg1=10, arg2=20 func1 was passed arg1=20 func3 was passed x=7, y=14 func2 was passed arg1=14, arg2=7 func1 was passed arg1=7 func1 was passed arg1=7 func1 was passed arg1=14