Functions Overview CSCE 121 J. Michael Moore Strongly influenced by slides created by Bjarne Stroustrup and Jennifer Welch
Spaghetti Code Code can become cumbersome/long. What to do? Break it up into parts / subroutines A subroutine is a piece of code that accomplishes a task. When the task returns a value it is like a function. But not all subroutines need to return a value…
Functions (i.e. C++ Subroutines) A named sequence of statements Can return a result Standard library provides lots of functions We can write our own functions also
Recall Programming Goals Correctness Efficiency Robustness Readability Reuse Modularity
Benefits of Functions Correctness, Modularity Chop a program into manageable parts Divide and conquer Model problem domain Name logical operations A function should do one thing well Improves readability of program Can be useful in many places in program Avoid having to copy same code Ease testing, maintenance, division of labor Modularity, Robustness Readability Reuse, Correctness, Robustness Correctness, Robustness Zybooks: Reasons for defining functions…
Rules of Thumb Keep functions small (about one screen) Each function should do a single well-defined task Makes them easier to understand, specify, and debug