Functions

Functions are an amazing tool that we can use to organize, simplify, and reuse the code that we write. We organize our code by pulling everything out of main, grouping code into more logical chunks. We simplify our code because smaller pieces of code are easier to write and, perhaps increasingly importantly, easier to debug. Wouldn’t you much rather debug something that’s breaking that consists only of 10 lines of code, rather than 100 or 1000? We can reuse our code by writing a function once and then directing our other programs to use the function that we wrote a single time. In fact, every time you use the CS50 Library that’s what you do. We wrote those functions once, in 2009, and now they can be reused. We don’t have to copy the lines of code that comprise things like get_int(); we can just rely on the fact that they once were written and now exist in a file. In this section, we discuss using functions – declaring, defining, and calling them – and how to make use of passing information back and forth between functions by way of return statements.