Lec 02 - Functions and Types
Last updated
Last updated
Slides:
Thinking in terms of functions has the advantage that is: given a function, we only need to worry about what it does, but not how it is done. We can treat a function as a black box with well-defined behavior -- given one or more inputs, it will produce a value satisfying certain conditions, i.e., it solves a computational problem.
In fact, a C program is just a collection of functions calling each other.
To make the functions that you write reusable and composable, you should create your functions in such a way that it does one thing and one thing only.
Recall from Unit 1 that machine code and data manipulated by machine code are all stored as a sequence of binaries, 1s and 0s, in the memory. Each unit of either 1 or 0 is known as a bit. 8 bits form a byte.
Remember from Lec 01 - Computational Problem Solving that the value of a variable is stored in a memory location as a sequence of bits. These bits have to be interpreted by the machine code to be given a meaning. Does a sequence of 1s and 0s represent an integer? A pixel of an image? A sound sample in an audio clip? A month? As a programmer, we have to tag the variable with its type, so that the machine code knows how to interpret the sequence of bits. In addition, the type also tells the machine code, how many bits "belong" to this variable. The number of bits of a type is also known as the size of a type.
If we only expect a variable to hold an integer, we should not choose a type that represents real numbers.
In C, we have to associate every variable with a type, and once a variable is declared with a type, the type cannot be changed.
This behavior is known as static typing. Some programming languages, such as Javascript and Python, are dynamically typed. The type of a variable may change depending on the value the variable is assigned to.