HIGH-LEVEL PROGRAMMING**
In the last chapter, we looked at the fundamentals of software: machine code that runs on processors, and assembly language, a human-readable representation of machine code. Although eventually all software must take the form of machine code, most software developers work at a higher, more abstract level. In this chapter, you learn about high-level programming. We cover an overview of high-level programming, discuss common elements found across various programming languages, and look at example programs.
High-Level Programming Overview
Although it’s possible to write software in assembly language (or even machine code!), doing so is time-consuming and error-prone, and it results in software that is hard to maintain. Furthermore, assembly language is specific to a CPU architecture, so if an assembly developer wishes to run their program on another type of CPU, the code must be rewritten. To address these shortcomings, high-level programming languages were developed; these allow programs to be written in a language that is independent from a specific CPU and is syntactically closer to human language. Many of these languages require a compiler , a program that converts high-level program statements to machine code for a specific processor. Using a high-level language, a software developer can write a program once and then compile it for multiple types of processors, sometimes with little or no change to the source code.
The output of a compiler is an object file that contains machine code for a specific processor. As we covered in Project #12 , object files aren’t in the correct format for a computer to execute. Another program, called a linker , is used to convert one or more object files into an executable file that the operating system can then run. The linker can also bring in other libraries of compiled code when needed. The process of compiling and linking is illustrated in Figure 9-1 .
Figure 9-1: Building executable software from source code
The process of compiling and linking is referred to as building software. However, in common usage, software developers sometimes speak of compiling their code when they really mean the entire process of compiling, linking, and any other steps required to get their code into its final form. Compilers often invoke the linking step automatically, making it less visible to the software developer.
Introduction to C and Python
The best way to learn about high-level programming is to examine programming languages and write some programs in those languages. For this chapter, I’ve chosen two high-level languages: C and Python. Both are powerful and useful, and they illustrate how programming languages tend to provide similar functionality but in different ways. Let’s begin with a brief introduction to each.
The C programming language dates back to the early 1970s, when it was used to write a version of the Unix operating system. Despite being a high-level language, C isn’t that far removed from underlying machine code, making it a great choice for operating system development or other software that interfaces directly with hardware. An updated version of C known as C++ came about in the 1980s. C and C++ are powerful languages that can be used to accomplish nearly anything. However, these languages are complex and don’t provide many safeguards against programmer mistakes. They remain a popular choice for programs that need to interface with hardware and those that require high performance, such as games. C is also useful for educational purposes, providing a straightforward mapping between low-level and high-level concepts, which is why I chose it for this chapter.
Compared to C, the Python programming language is further removed from underlying hardware. Initially released in the 1990s, Python has grown in popularity over the years. It’s known for being easy to read and simple for beginners, while still providing everything necessary to support complex software projects. Python has a “batteries included” philosophy, meaning a standard distribution of Python includes a library of helpful capabilities that developers can easily use in their projects. The straightforward nature of Python makes it a good choice for teaching concepts of programming.
Let’s now look at elements found across most high-level programming languages. The goal isn’t to teach you to be a programmer in a specific language, but to instead familiarize you with the ideas commonly found in programming languages. Remember that the capabilities found in high-level programming languages are abstractions of CPU instructions. As you know, CPUs provide instructions for memory access, math and logic operations, and control of program flow. Let’s look at how high-level languages expose these underlying capabilities.
Comments
Let’s begin with a feature of programming languages that doesn’t actually instruct the CPU to do anything! Nearly all programming languages provide a way to include comments in code. A comment is text in source code that provides some insight into the code. Comments are intended to be read by other developers and are typically ignored by the compiler; they have no effect on the compiled software. In the C programming language, comments are specified like so:
/*
This is a C-style comment.
It can span multiple lines.
*/
// This is a single-line C comment, originally introduced in C++.
Python uses the hash character for comments, like this:
# This is a comment in Python.
Python doesn’t provide any particular support for multiline comments; a programmer can simply use multiple single-line comments, one after another.
Variables
Memory access is a fundamental capability of processors, and therefore it must be a feature of high-level languages as well. The most basic way that programming languages expose memory is through variables. A variable is a named storage location in memory. Variables allow programmers to give a name to a memory address (or range of memory addresses) and then access data at that address. In most programming languages, variables have a type , indicating what sort of data they hold. For example, a variable may be an integer type or a text string type. Variables also have a value , which is the data stored in memory. Although it’s often hidden from the programmer, variables also have an address , the location in memory where the variable’s value is stored. Lastly, variables have scope , meaning they can only be accessed from certain parts of the program, the parts where they are “in scope.”
Variables in C
Let’s look at an example of a variable in the C programming language.
// Declare a variable and assign it a value in C.
int points = 27;
This code declares a variable named points with a type of int , which in the C language means the variable holds an integer. The variable is then assigned a value of 27 . When this code runs, the value of 27 decimal is stored at a memory address, but the developer doesn’t need to worry about the specific address where the variable is stored. Most C compilers today treat an int as a 32-bit number, so at runtime (the time when a program executes) 4 bytes are allocated for this variable (4 bytes × 8 bits per byte = 32 bits), and the memory address of the variable refers to the first byte.
Let’s now declare a second variable and assign it a value; then we can look at how the two variables are allocated in memory.
// Two variables in C
int points = 27;
int year = 2020;
Now we have two variables, points and year , declared one after another. Both are integers, so they each require 4 bytes for storage. The variables can be stored in memory as shown in Table 9-1 .
Table 9-1: Variables Stored in Memory
| Address | Variable name | Variable value |
|---|---|---|
| 0x7efff1cc | ? | ? |
| 0x7efff1d0 | year | 2020 |
| 0x7efff1d4 | points | 27 |
| 0x7efff1d8 | ? | ? |
The memory addresses used in Table 9-1 are just examples; the actual addresses vary depending on the hardware, operating system, compiler, and so forth. Note that the addresses increment by four, since we’re storing 4-byte integers. The addresses before and after the known variables have a question mark for the variable name and value, since based on the preceding code, we don’t know what might be stored there.
NOTE
Please see Project #14 on page 184 , where you can look at variables in memory .
As the name variable implies, the value of a variable can change. If our earlier C program needed to set the value of points to another value, we could simply do this later in the program:
// Setting a new points value in C
points = 31;
Note that unlike our previous code snippet in C, this code does not specify int or any other type before the variable name. We only need to specify the type when the variable is initially declared. In this case, the variable was declared earlier, so here we just assign it a value. However, the C language requires that the variable’s type remain the same, so once points is declared as an int , only integers can be assigned to that variable. Attempting to assign another type, such as a text string, results in a failure when the code is compiled.
Variables in Python
Not all languages require a declaration of type. Python, for example, allows a variable to be declared and assigned like so:
# Python allows new variables without specifying a type.
age = 22
Now, in this case, Python recognizes that the type of data is an integer, but the programmer doesn’t have to specify this. Unlike in C, the variable’s type can change over time, so the following is valid in Python:
# Assiging a variable a value of a different type is valid in Python.
age = 22
age = 'twenty-two'
Let’s take a closer look at what is actually happening in this example. A Python variable has no type, but the value to which it refers does have a type. This is an important distinction: the type is associated with the value, not the variable. A Python variable can refer to a value of any type. So when the variable is assigned a new value, it isn’t really that the variable’s type is changing, but rather that the variable has been bound to a value of a different type. Contrast this with C, where the variable itself has a type and can only hold values of that type. This difference explains why a variable in Python can be assigned values of different types, whereas a variable in C cannot.
NOTE
Please see Project #15 on page 186 , where you can change the type of value referenced by a variable in Python .
Stack and Heap Memory
When a programmer uses a high-level language to access memory, the details of how that memory is managed behind the scenes is somewhat obscured, depending on the programming language in use. A programming language like Python makes the details of memory allocation nearly invisible to the programmer, whereas a language like C exposes some of the underlying memory management mechanisms. Whether the details are exposed to the programmer or not, programs commonly make use of two types of memory: stack and heap.
The Stack
The stack is an area of memory that operates on a last-in first-out (LIFO) model. That is, the last item put on the stack is the first item that comes off the stack. You can think of a memory stack as being like a stack of plates. When you add to a stack of plates, you add the newest plate to the top. When the time comes to take a plate from the stack, you remove the top plate first. This does not mean that the items on the stack can only be accessed (read or modified) in LIFO order. In fact, any item currently on the stack can be read or modified at any time. However, when it comes time to remove unneeded items from the stack, the items are discarded from the top down, meaning the last item placed on the stack is the first to go.
The memory address of the value on the top of the stack is stored in a processor register known as the stack pointer . When a value is added to the top of the stack, the stack pointer’s value is adjusted to increase the size of the stack and make room for the new value. When a value is removed from the top of the stack, the stack pointer is adjusted to decrease the size of the stack.
The compiler generates code that uses the stack to track the state of a program’s execution and as a place to store local variables. The mechanics of this are transparent to a programmer in a high-level language. Figure 9-2 provides a look at how a C program uses the stack to hold the two local variables that we covered earlier in Table 9-1 .
Figure 9-2: Stack memory is used to hold variable values in a program written in C.
In Figure 9-2 , the points variable is declared first and assigned a value of 27 , a value that is stored on the stack. Next, the year variable is declared and assigned a value of 2020 . This second value is placed “above” the prior value on the stack. Additional values will continue to be added to the top of the stack until they are no longer needed, at which point they will be removed from the stack. Keep in mind that each slot in the diagram is just a location in memory with an assigned memory address, although the addresses aren’t shown in the diagram. You may be surprised to hear that in many architectures, the memory addresses assigned to the stack actually decrease as the stack grows. In this example, that means that the year variable has a lower memory address than the points variable.
Stack memory is fast and well suited for small memory allocations that have limited scope. A separate stack is made available to each thread of execution in a program. We’ll cover threads in more detail in Chapter 10 , but for now you can think of threads as parallel tasks within a program. The stack is a limited resource; there’s a limit to how much memory is allocated to the stack. Putting too many values on the stack results in a failure known as a stack overflow .
The Heap
The stack is meant to hold small values that only need to be temporarily available. For memory allocations that are large or need to persist for a longer time, the heap is a better fit. The heap is a pool of memory that’s available to a program. Unlike the stack, heap memory doesn’t work on a LIFO model; there is no standard model for how heap memory is allocated. Whereas stack memory is specific to a thread, allocations made from the heap can be accessed by any of the program’s threads.
Programs allocate memory from the heap, and that memory usage persists until it’s freed by the program or the program terminates. To free a memory allocation simply means to release it back to the pool of available memory. Some programming languages automatically free heap memory when an allocation is no longer referenced; one common approach for doing this is known as garbage collection . Other programming languages, like C, require the programmer to write code to free heap memory. A memory leak occurs when unused memory isn’t freed.
In the C programming language, a special kind of variable called a pointer is used to track memory allocations. A pointer is simply a variable that holds a memory address. The pointer value (a memory address) can be stored in a local variable on the stack, and that value can refer to a location in the heap, as illustrated in Figure 9-3 .
Figure 9-3: The pointer variable named data is on the stack and points to an address in the heap.
In Figure 9-3 we have a code snippet that declares a variable called data . This variable is of type void * , which means it’s a pointer (indicated by * ) that points to a memory address that can hold any type of data ( void means the type isn’t specified). Because data is a local variable, it is allocated on the stack. The next line of code makes a call to malloc , a function in C that allocates memory from heap. The program is asking for 512 bytes of memory, and the malloc function returns the address of the first byte of the newly allocated memory. That address is stored in the data variable, on the stack. So we end up with a local variable at an address on the stack that holds the address of an allocation on the heap.
NOTE
Please see Project #16 on page 187 , where you can see for yourself how variables are allocated in a running program .
Math
Since processors provide instructions for performing mathematical operations, high-level languages do too. In contrast to programming in assembly language, where specific named instructions are required for math (such as the subs instruction for subtraction on ARM processors), high-level languages generally include symbols that represent common mathematical operations, making it simple to perform math in code. A large number of programming languages, including C and Python, use the same operators for addition, subtraction, multiplication, and division, as shown in Table 9-2 .
Table 9-2: Common Math Operators
| Operation | Operator |
|---|---|
| Addition | + |
| Subtraction | - |
| Multiplication | * |
| Division | / |
Another common convention across multiple programming languages is to use the equals sign ( \= ) to represent an assignment rather than equality. That is, a statement like x = 5 means to set the value of x to 5. Assigning the result of a mathematical operation is represented in a natural way, such as in these statements:
// Addition is easy in C.
cost = price + tax;
# Addition is easy in Python too.
cost = price + tax
So far, we’ve focused on integer math, which is common in computing. However, computers and high-level languages also support something called floating-point arithmetic . Unlike integers that represent whole numbers, floating-point values can represent fractions. Some programming languages hide the details of this, but internally CPUs use different instructions for floating-point math than for integer math. In C, floating-point variables are declared using a floating-point type such as float or double , as shown here:
// Declaring a floating-point variable in C
double price = 1.99;
On the other hand, Python infers type for its variables, so both integers and floating-point values are declared in the same way:
# Declaring integer and floating-point varibles in Python
year = 2020 # year is an int
price = 1.99 # price is a float
The differences in integers verses floating-point numbers can lead to unexpected results sometimes. For example, let’s say you have the following C code:
// Dividing integers in C
int x = 5;
int y = 2;
int z = x / y;
What would you expect the value of z to be? It turns out that since all the numbers involved are integers, z ends up with a value of 2 . Not 2.5 , but 2 . As an integer, z cannot hold fractional values.
Now what if we changed the code slightly, like so:
// Dividing integers in C, result stored in a float
int x = 5;
int y = 2;
float z = x / y;
Note that z now has a type of float . Now what would you expect the value of z to be? Interestingly, z is now equal to 2.0 ; it still isn’t 2.5 ! This is because the division operation occurred with two integers, so the result was an integer too. The division result was 2 , and when it was assigned to floating-point variable z , it was given the value 2.0 . The C language is very literal; it’s compiled into instructions that closely mirror what the programmer said to do. This is great for programmers who need fine-grained control of processing, but not always so great for programmers who expect more intuitive behavior from their programming language.
Python tries to be more helpful, automatically assigning a type that allows for fractional results in a situation like this. If we write an equivalent version of this code in Python, the result stored in z will be 2.5 .
# Dividing integers in Python
# z will be 2.5 and its inferred type is float
x = 5
y = 2
z = x / y
Some languages provide mathematical operators that are abbreviated ways of stating an operation. For example, C provides increment (add 1) and decrement (subtract 1) operators, as shown here:
// In C, we can add one to a variable the long way,
x = x + 1;
// or we can use this shortcut to increment x.
x++;
// On the other hand, this will decrement x.
x--;
NOTE
Fun fact: the name of the programming language C++ is meant to convey the idea that it’s an improvement upon, or an increment of, the C programming language .
Python also provides some shortcut operators for math. The += and -= operators allow programmers to add to or subtract from a variable. For example:
# In Python, we can add 3 to a variable like this...
cats = cats + 3
# Or we can do the same thing with this shortcut...
cats += 3
The += and -= operators work in C as well.
Logic
As we covered earlier, processors are very good at performing logical operations, since logic is the foundation for digital circuits. As you’d expect, programming languages also provide the capability to handle logic. Most high-level languages provide two kinds of operators that deal in logic: bitwise operators, which deal with the bits of integers, and Boolean operators, which deal with Boolean (true/false) values. The terminology here can be confusing, since different programming languages use different terms. Python uses “bitwise” and “Boolean,” whereas C uses “bitwise” and “logical,” and other languages use still other terms. Let’s stick with “bitwise” and “Boolean” here.
Bitwise Operators
Bitwise operators act on the individual bits of integer values and result in an integer value. A bitwise operator is like a mathematical operator, but instead of adding or subtracting, it performs an AND, OR, or other logical operation on the bits of integers. These operators work according to the truth tables covered in Chapter 2 , performing the operation on all the bits in the integer in parallel.
Many programming languages, including C and Python, use the set of operators shown in Table 9-3 for bitwise operations.
Table 9-3: Bitwise Operations as Commonly Expressed in Programming Languages
| Bitwise operation | Bitwise operator |
|---|---|
| AND | & |
| OR | | | | XOR | ^ | | NOT (complement) | ~ |
Let’s look at a bitwise example in Python.
# Python does bitwise logic.
x = 5
y = 3
a = x & y
b = x | y
The result of the code above is that a is 1 and b is 7. Let’s look at those operations in binary ( Figure 9-4 ) to make it clear why this is so.
Figure 9-4: Bitwise AND, OR operations on 5 and 3
Take a look at the AND operation in Figure 9-4 first; recall from Chapter 2 that AND means that the result is 1 when both inputs are 1. Here we look at the bits one column at a time, and as you can see, only the rightmost bit is 1 for both inputs. Therefore, the AND result is 0001 binary, or 1 decimal. Therefore, a is assigned a value of 1 in the preceding code.
On the other hand, OR means that the result is 1 if either input (or both inputs) is 1. In this example, the rightmost three bits are all 1 in one input or the other, so the result is 0111 binary, or 7 decimal. Therefore, b is assigned a value of 7 in the preceding code.
EXERCISE 9-1: BITWISE OPERATORS
Consider the following Python statements. What will be the values of a , b , and c after this code executes?
x = 11
y = 5
a = x & y
b = x | y
c = x ^ y
The answer can be found in Appendix A .
Boolean Operators
The other kind of logical operator in high-level programming languages is the Boolean operator . These operators work on Boolean values and result in a Boolean value.
Let’s take a moment to talk about Boolean values. A Boolean value is either true or false. Different programming languages represent true or false in different ways. A Boolean variable is a named memory address that holds a Boolean value of true or false. For example, we could have a variable in Python that tracks whether an item is on sale: item_on_sale = True .
An expression can evaluate to true or false without the result being stored in a variable. For example, the expression item_cost > 5 evaluates to either true or false at runtime depending on the value of the item_cost variable.
Boolean operators allow us to perform a logical operation like AND, OR, or NOT on Boolean values. For example, we can check if two conditions are both true using Python’s Boolean AND operator: item_on_sale and item_cost > 5 . The expressions to the left and right of and evaluate to Boolean values, and in turn, the entire expression evaluates to a Boolean value. Here C and Python use different operators, as shown in Table 9-4 .
Table 9-4: Boolean Operators in C and Python Programming Languages
| Boolean operation | C operator | Python operator |
|---|---|---|
| AND | & & | and |
| OR | || | or | | NOT | ! | not |
While we’re on the subject of operators that return Boolean values, a comparison operator compares two values and evaluates to true or false as the result of the comparison. For example, the greater than operator allows us to compare two numbers and determine if one is larger than the other. Table 9-5 shows comparison operators used in both C and Python.
Table 9-5: Comparison Operators in C and Python Programming Languages
| Comparison operation | Comparison operator |
|---|---|
| EQUALITY | \== |
| NOT EQUAL | != |
| GREATER THAN | > |
| LESS THAN | < |
| GREATER THAN OR EQUAL | >= |
| LESS THAN OR EQUAL | <= |
You’ve already seen one of these in use, in our earlier example of item_cost > 5 . Pay attention to the equality operator. Both C and Python use a double equals sign to represent an equality comparison, and they use a single equals sign to represent an assignment. That means x == 5 is a comparison that returns true or false (is x equal to 5 ?), whereas x = 5 is an assignment that sets the value of x to 5 .
Program Flow
Boolean and comparison operators allow us to evaluate the truth of an expression, but that alone isn’t very useful. We need a way to do something in response! Program flow , or control flow , statements allow us to do just that, altering the behavior of a program in response to some condition. Let’s look at some common program flow constructs found across programming languages.
If Statements
An if statement , often coupled with an else statement , allows the programmer to do something if some condition is true. In turn, the else statement allows the program to do something different if the condition is false. Here’s an example in Python:
# Age check in Python
❶ if age < 18:
❷ print('You are a youngster!')
❸ else:
❹ print('You are an adult.')
In this example, the first if statement ❶ checks if the age variable refers to a value that’s less than 18. If so, it prints a message indicating that the user is young ❷ . The else statement ❸ tells the program to print a different message if age is 18 or greater ❹ .
Here is the same “age check” logic, this time written in C:
// Age check in C
if (age < 18)
❶ {
printf("You are a youngster!");
❷ }
else
{
printf("You are an adult.");
}
In the C example, note the curly braces used after the if statement ❶❷ . These mark off a block of code that should execute in response to the if . In C, a code block can consist of multiple lines of code, although the braces can be omitted when the block consists of a single line. Python doesn’t use braces to delimit a block of code; it uses indentation instead. In Python, contiguous lines at the same level of indentation (say, four spaces) are considered part of the same block.
Python also includes an elif statement, which means “else if.” An elif statement is only evaluated if the preceding if or elif statement was false.
# A better age check in Python
if age < 13:
print('You are a youngster!')
elif age < 20:
print('You are a teenager.')
else:
print('You are older than a teen.')
The same thing can be accomplished in C by using an else coupled with an if :
// A better age check in C
if (age < 13)
printf("You are a youngster!");
else if (age < 20)
printf("You are a teenager!");
else
printf("You are older than a teen.");
Note that I’ve also omitted the curly braces since all my code blocks are single lines.
Looping
Sometimes a program needs to perform a certain action over and over. A while loop allows code to run repeatedly until some condition is met. In the following Python example, a while loop is used to print the numbers from 1 to 20.
# Count to 20 in Python.
n = 1
while n <= 20:
print(n)
n = n + 1
Initially, the variable n is set to 1 . The while loop begins, indicating that the loop should run while n is less than or equal to 20 . Since n is 1 , it meets that requirement, so the body of the while loop runs, printing the value of n and adding 1 to it. Now n is equal to 2 , and the code goes back to the top of the while loop. This process continues until n is equal to 21 , at which point it no longer meets the requirements of the while loop, so the loop ends.
The following is the same thing implemented in C.
// Count to 20 in C.
int n = 1;
while(n <= 20)
{
printf("%d\n", n);
n++;
}
In both examples, the body of the while loop increments the value of n . There’s actually a cleaner way to do this. A for loop allows iteration over a range of numbers or a collection of values so that the programmer can perform some operation on each. Here we have an example in C that prints 1 through 10.
// C uses a for loop to iterate over a numeric range.
// This will print 1 through 10.
for( ❶ int x = 1; ❷ x <= 10; ❸ x++)
{
❹ printf("%d\n", x);
}
The for loop declares x and sets its initial value to 1 ❶ , states that the loop will continue while x is less than or equal to 10 ❷ , and finally declares that x should be incremented after the body of the loop runs ❸ . By putting all of this information in a for statement on a single line, we can more easily see the conditions under which the loop will run. The body of the for loop simply prints the value of x ❹ .
Python takes a different approach with its for loops, allowing the program to take an action repeatedly on every item in a collection of values. The following Python example prints out the names of animals in a list.
# Python uses a for loop to iterate over a collection.
# This will print each animal name in animal_list.
animal_list = ['cat', 'dog', 'mouse']
for animal in animal_list:
print(animal)
First, a list of animal names is declared and assigned to a variable named animal_list . In Python, a list is an ordered collection of values. Next, the for loop states that the code block runs once for each item in animal_list , and each time the code runs, the current value in the list is assigned to the animal variable. So the first time the body of the loop runs, animal is equal to cat , and the program prints cat . The next time through dog prints, and the final time mouse prints.
Functions
Looping allows a set of instructions to run multiple times in a row. However, it’s also common for a program to run a particular set of instructions multiple times, but not necessarily in a loop. Instead, such instructions may need to be invoked from different parts of the program, at different times, and with varying inputs and outputs. When a programmer realizes that the same code is needed in multiple places, they may write that code as a function. A function is a set of program instructions that may be invoked, or called, by other code. Functions optionally take inputs (known as parameters ) and return an output (known as a return value ). Different high-level languages use different terms for a function, including subroutine , procedure , or method . In some cases, these various names actually convey slightly different meanings, but for our purposes, let’s just stick with function.
Converting a character string to lowercase, printing text to the screen, and downloading a file from the internet are all examples of what you can do with reusable code in the form of a function. Programmers want to avoid typing out the same code multiple times. Doing so means maintaining several copies of the same code and increasing the overall size of a program. This violates a software engineering principle known as don’t repeat yourself (DRY) that encourages a reduction of duplicative code.
Functions are another example of encapsulation. We saw encapsulation earlier in the context of hardware, and here we see it again, this time in software. Functions encapsulate the internal details of a block of code while providing an interface for making use of that code. A developer who wants to use a function only needs to understand its inputs and outputs; a full understanding of the function’s internal workings isn’t needed.
Defining Functions
A function must be defined before it can be used. Once defined, you use a function by calling it. A function definition includes the name of the function, the input parameters, the program statements for the function (called the body of the function), and in some languages, the return value type. Here we have a sample C function that calculates the area of a circle, given its radius.
// C function to calculate the area of a circle
❶ double ❷ areaOfCircle( ❸ double radius)
{
double area = 3.14 * radius * radius;
❹ return area;
}
The double type at the beginning ❶ indicates that the function returns a floating-point number ( double is one of the floating-point types in C). The function has a name, areaOfCircle ❷ , meant to convey what the function does—in this case, calculate the area of a circle. The function takes one input parameter named radius ❸ , also of type double .
Between the opening and closing curly braces we have the body of the function, which defines exactly how the function works. We declare a local variable named area . It’s also of type double . The area is calculated as π × radius 2 and assigned to the area variable. Finally, the function returns the value of the area variable ❹ . Note that the area variable’s scope is limited; it cannot be accessed outside of this function. When the function returns, the local variable area is discarded (it was probably stored on the stack), but its value is returned to the caller, likely via a processor register.
The following is a similar area function, this time written in Python.
# Python function to calculate the area of a circle
def area_of_circle(radius):
area = 3.14 * radius * radius
return area
Let’s compare the two function examples. Both calculate the area as π × radius 2 and then return that value. Both take one input parameter named radius . The C version explicitly defines the return type as double and the type of radius as double , while the Python version doesn’t require the types to be declared. Python indicates that a function definition is about to begin with the def keyword.
Calling Functions
Defining a function in a program isn’t enough to ensure that function will run. A function definition simply makes the code available for other code to invoke when needed. Such an invocation is known as a function call . The calling code passes any needed parameters and hands control over to the function. The function then executes its code and returns control (and any output) back to the caller. The following demonstrates calling our example function in C:
// Calling a function twice in C, each time with a different input
double area1 = areaOfCircle(2.0);
double area2 = areaOfCircle(38.6);
and in Python:
# Calling a function twice in Python
area1 = area_of_circle(2.0)
area2 = area_of_circle(38.6)
Once the function returns, it’s up to the calling code to store the returned value somewhere. Variables area1 and area2 are declared in both examples to hold the return values from the function calls. In both languages, area1 is 12.56 and area2 is 4,678.4744. Actually, the calling code can just ignore the returned value and not assign it to a variable, but that is not very useful, considering this function’s purpose. Figure 9-5 illustrates how calling a function temporarily cedes control to that function.
Figure 9-5: Calling a function
In Figure 9-5 , the Python code on the left calls the area_of_circle function, passing it an input radius parameter value of 2.0 . The code on the left then waits until the function on the right completes its work. Once the function returns, the code on the left stores the returned value in variable area1 , and it then resumes execution.
Using Libraries
Although programmers do define functions for their own use, an important part of programming is knowing how to best leverage functions that other people have already written. Programming languages usually include a large set of functions known as the standard library for that language. In this context, a library is a collection of code intended to be used by other software. Both C and Python include standard libraries that provide functions for things such as printing to the console, working with files, and text processing. Python’s standard library is particularly extensive and well-regarded. Although not always the case, most implementations of a language include that language’s standard library, so programmers can rely on those functions.
NOTE
Please see Project #17 on page 189 , where you can use what you’ve learned to write a simple guessing game in Python. This includes using the Python standard library .
Outside of the standard library, additional libraries of functions are also available for many programming languages. Developers write libraries for others to use and share them in the form of source code or as compiled files. These libraries are sometimes shared informally, and certain programming languages have a well-known, accepted mechanism for publishing libraries. A shared set of libraries is known as a package , and a system for sharing such packages is known as a package manager . Several package managers are available for C, but none of them is universally accepted as a standard by C programmers. Python’s included package manager is called pip . pip makes it easy to install community-developed software libraries for Python, and it’s commonly used by Python developers.
Object-Oriented Programming
Programming languages are designed to support specific paradigms , or approaches, to programming. Examples include procedural programming, functional programming, and object-oriented programming. A language may be designed to support one or multiple paradigms, and it is up to the software developer to use the language in a way that fits a certain paradigm. Let’s take a look at one popular paradigm: object-oriented programming , an approach to programming in which code and data are grouped together in a construct known as an object . Objects are meant to represent a logical grouping of data and functionality in a way that models real-world concepts.
Object-oriented programming languages commonly use a class-based approach. A class is a blueprint for an object. An object created from a class is said to be an instance of that class. Functions defined in a class are known as methods , and variables declared in a class are known as fields . In Python, fields that have different values for each instance of a class are called instance variables , whereas fields that have the same value across all instances of the class are called class variables .
For example, a class could be written that describes a bank account. The bank account class might have a field for the balance, a field for the holder’s name, and methods for withdrawing and depositing money. The class describes a generic bank account, but no specific instance of a bank account exists until a bank account object is created from that class. This is illustrated in Figure 9-6 .
Figure 9-6: Bank account objects are created from a bank account class.
As you can see in Figure 9-6 , the BankAccount class describes the fields and methods of the bank account, providing us with an understanding of what a bank account is like. Two objects, instances of the BankAccount class, have been created. These objects are specific bank accounts, with names and balances assigned. We can use each object’s withdraw or deposit method to modify its balance field. In Python, depositing into a bank account object named myAccount would look like this, resulting in an increase of 25 to its balance field:
myAccount.deposit(25)
NOTE
Please see Project #18 on page 190 , where you can try a Python implementation of the bank account class just described .
Compiled or Interpreted
As mentioned earlier, source code is the text of a program as originally written by developers, and it usually isn’t written in a programming language that CPUs understand directly. CPUs only understand machine language, so additional steps are required: source code must be either compiled to machine code or interpreted by other code at runtime.
In a compiled language , like C, source code is converted into machine instructions that can be directly executed by a processor. That process was described earlier in this chapter in “High-Level Programming Overview” on page 160 . Source code is compiled during the development process, and the compiled executable files (sometimes called binaries ) are delivered to end users. When end users run binaries, they don’t need access to the source code. Compiled code tends to be fast, but it only runs on the architecture for which it was compiled. Figure 9-7 shows an example of how a developer would compile and run a C program from a command line using the GNU C Compiler ( gcc ).
Figure 9-7: Compiling a C source file to an executable file that can run on its own
In an interpreted language , like Python, the source code is not compiled ahead of time. Instead, it is read by a program called an interpreter that reads and executes the program’s instructions. It’s the interpreter’s machine code that actually runs on the CPU. Developers of code in interpreted languages can distribute their source code and end users can run it directly, without the need for a potentially complex compilation step. In this scenario, the developers don’t need to worry about compiling their code for lots of different platforms—as long as the user has the appropriate interpreter on their system, they can run the code. In this way, the distributed code is platform-independent.
Interpreted code tends to run more slowly than compiled code due to the overhead of interpreting the code as it runs. Distributing interpreted code works best when the user already has the required interpreter installed or the user is technically proficient enough that installing an interpreter isn’t a barrier. Otherwise, the developer needs to either bundle the interpreter with their software or guide the user through installing the interpreter. Figure 9-8 shows an example of running a Python program from a command line, assuming the Python version 3 interpreter is already installed. Note how the Python source code in hello.py is given directly to the interpreter—no intermediate step required.
Figure 9-8: The Python interpreter runs Python source code.
Some languages use a system that’s a hybrid of these two approaches. Such languages compile to an intermediate language , or bytecode . Bytecode is similar to machine code, but rather than targeting a specific hardware architecture, bytecode is designed to run on a virtual machine, as illustrated in Figure 9-9 .
Figure 9-9: A bytecode compiler turns source code into bytecode that runs inside a virtual machine.
In this context, a virtual machine is a software platform designed to run other software. The virtual machine provides a virtual CPU and execution environment, abstracting the details of the real underlying hardware and operating system. For example, Java source code is compiled to Java bytecode, which then runs within the Java virtual machine. Similarly, C# source code is compiled to Common Intermediate Language and runs in the .NET Common Language Runtime (CLR) virtual machine. CPython, the original implementation of Python, actually converts Python source code to bytecode before running it, although this is an implementation detail of the CPython interpreter and mostly hidden from Python developers. Programming languages that use bytecode retain the platform-independence of interpreted languages while preserving some of the performance gains of compiled code.
Calculating a Factorial in C
To wrap up our look at high-level programming, let’s now examine an implementation of the factorial algorithm, this time in the C language. We did this before in ARM assembly, so seeing the same logic in C should serve as a good comparison between assembly language and a high-level language. This C code uses several of the concepts we just covered. I chose to use C rather than Python because it’s a compiled language, and we can examine the compiled machine code. Here’s a simple C function that calculates the factorial of a number:
// Calculate the factorial of n.
int factorial(int n)
{
int result = n;
while(--n > 0)
{
result = result * n;
}
return result;
}
Other code can call this function, passing the n parameter as the value whose factorial should be calculated. The function then internally calculates the factorial value, storing it in the local variable result and returning the calculated value to the caller. As we did with the assembly code in Chapter 8 , let’s again use an exercise to explore this code in depth.
EXERCISE 9-2: RUN A C PROGRAM IN YOUR MIND
Try running the preceding factorial function in your head or use pencil and paper. Assume an input value of n = 4. When the function returns, the returned result should be the expected value of 24. I recommend that for each line, you keep track of the values of n and result before and after the statement completes. Work through the code until you reach the end of the while loop and see if you get the expected result. The answer is in Appendix A .
Note that the condition of the while loop ( --n > 0) places the decrement operator ( -- ) before the variable n . This means that n is decremented before its value is compared to 0. This happens each time the while loop condition is evaluated.
I hope that you find the C version of our algorithm more readable than the ARM assembly version! The other major advantage of this version of our factorial code is that it isn’t tied to a specific processor type. It could be compiled for any processor, given an appropriate compiler. If you compile the earlier C code for an ARM processor, you see machine code generated that’s similar to the ARM assembly we examined earlier. You’ll get a chance to do that in Project #19 , but for now I’ve compiled and disassembled the code for you:
Address Assembly
0001051c sub r3, r0, #1
00010520 cmp r3, #0
00010524 bxle lr
00010528 mul r0, r3, r0
0001052c subs r3, r3, #1
00010530 bne 00010528
00010534 bx lr
As you can see, the code generated from the C source is quite similar to the assembly factorial example we covered in Chapter 8 . There are some differences, but the specifics aren’t relevant to our discussion. The thing to note here is that a program can be written in a high-level language like C, and a compiler can do the hard work of translating the high-level statements to machine code. You can see how working in a high-level language can simplify things for a developer, but in the end, we still end up with bytes of machine code, because that’s what a processor needs.
NOTE
Please see Project #19 on page 191 , where you can try compiling and then disassembling a factorial program in C .
Something interesting happened here, and I want to make sure you didn’t miss it. We started with source code written in the C programming language, compiled it into machine code, and then disassembled it into assembly language. The implication of this is that if you have a compiled program or software library on your computer, you can examine its code as assembly language! You may not have access to the original source code, but the assembly version of the program is within your grasp.
We’ve been looking at machine code and assembly language for the ARM processor specifically, but as mentioned earlier, one of the advantages of developing in a high-level language like C is that the same code can be compiled for a different processor. In fact, the same code can even be compiled for another operating system, as long as the code in question doesn’t use functionality that’s specific to a particular operating system. To illustrate this point, I’ve compiled the same factorial C code for a 32-bit x86 processor, this time on Windows rather than Linux. Here’s the generated machine code, shown as assembly language:
Address Assembly
00406c35 mov ecx,dword ptr [esp+4]
00406c39 mov eax,ecx
00406c3b jmp 00406c40
00406c3d imul eax,ecx
00406c40 dec ecx
00406c41 test ecx,ecx
00406c43 jg 00406c3d
00406c45 ret
I won’t elaborate on the details of this code, but feel free to research the x86 instruction set and interpret the code yourself. The main thing I hope you take away from this example is that high-level languages, like C, allow developers to write code that’s easier to understand than assembly and that can be easily compiled for various processors.
Summary
In this chapter we covered high-level programming languages. Such languages are independent from a specific CPU and syntactically closer to human language. You learned about common elements found across programming languages, such as comments, variables, functions, and looping capabilities. You saw how these elements are expressed in two programming languages: C and Python. Finally, we examined an example program in C, and you saw the disassembled machine code generated by compiling high-level code.
In the next chapter, we’ll cover operating systems. We’ll start with an overview of the capabilities provided by operating systems, learn about the various families of operating systems, and dive deeper into how operating systems work. Along the way you’ll have the opportunity to explore Raspberry Pi OS, a version of Linux tailored for the Raspberry Pi.
PROJECT #14: EXAMINE VARIABLES
Prerequisite: A Raspberry Pi, running Raspberry Pi OS. I recommend that you flip to Appendix B and read the entire “Raspberry Pi” section on page 341 if you haven’t already.
In this project, you’ll write high-level code that uses variables and examine how this works in memory. Use the text editor of your choice to create a new file called vars.c in the root of your home folder. Enter the following C code into your text editor (you don’t have to preserve indentation and empty lines, but be sure to maintain line breaks).
#include <stdio.h> ❶
#include <signal.h>
int main() ❷
{
int points = 27; ❸
int year = 2020; ❹
printf("points is %d and is stored at 0x%08x\n", points, &points); ❺
printf("year is %d and is stored at 0x%08x\n", year, &year);
raise(SIGINT); ❻
return 0;
}
Before continuing, let’s examine the source code. It begins by including a couple of header files ❶ . These files include details required by the C compiler about the printf and raise functions that are used later in the program. Next you see the main function defined ❷ ; this is the entry point of the program where execution begins. The program then declares two integer variables, points ❸ and year ❹ , and assigns values to them. It then prints out both the values of the variables and their memory addresses (in hexadecimal) ❺ . The raise(SIGINT) statement causes the program to halt execution ❻ . This is not something you normally do in code that end users run; it’s a technique we use here to assist with debugging.
Once the file is saved, use the GNU C Compiler ( gcc ) to compile your code into an executable file. Open a terminal on your Raspberry Pi and enter the following command to invoke the compiler. This command takes vars.c as an input, compiles and links the code, and outputs an executable file named vars .
$ gcc -o vars vars.c
Now try running the compiled code using the following command. The program should print out the values and addresses of the program’s two variables.
$ ./vars
Once you’ve confirmed that the program works, run it under the GNU Debugger ( gdb ) and examine the variables in memory.
$ gdb vars
At this point gdb has loaded the file but no instructions have run yet. From the (gdb) prompt, type the following to run the program, which will continue until the raise(SIGINT) statement is executed.
(gdb) run
Once the program returns to a (gdb) prompt, you should see a couple of lines where the values and memory addresses of the variables were printed. Following those lines, you may also see a potentially worrisome statement about “no such file or directory”—you can ignore it. It’s just the debugger trying to find some source code that isn’t on your system. The output you do need to pay attention to should look something like this:
Starting program: /home/pi/vars
points is 27 and is stored at 0x7efff1d4
year is 2020 and is stored at 0x7efff1d0
Now you know the memory addresses, and since you’re conveniently in the debugger, you’re ready to examine what’s stored at those addresses. In this output, you can see that year is stored at the lower address, and points is stored 4 bytes later, so you’ll dump out memory starting at the address of the year variable, 0x7efff1d0 in my case. Your address may be different. The following command dumps out three 32-bit values in memory, in hexadecimal, starting at address 0x7efff1d0 . Replace 0x7efff1d0 with the address of year on your system if they differ.
(gdb) x/3xw 0x7efff1d0
0x7efff1d0: 0x000007e4 0x0000001b 0x00000000
You can see here that the value stored at 0x7efff1d0 is 0x000007e4 . That’s 2020 in decimal, the expected year value. And the value stored 4 bytes later is 0x0000001b , or 27 decimal, the expected points value. The next value in memory happens to be 0 and isn’t one of our variables. Memory is usually examined in hexadecimal, but if you want to see these values in decimal, you can use the following command instead:
(gdb) x/3dw 0x7efff1d0
0x7efff1d0: 2020 27 0
You’re looking at memory in 32-bit (4-byte) chunks, since that’s the size of the variables used in this program. But memory is actually byte addressable, meaning each byte has its own address. That’s why points has an address 4 bytes greater than the address of year . Let’s look at the same memory range as a series of bytes instead:
(gdb) x/12xb 0x7efff1d0
0x7efff1d0: 0xe4 0x07 0x00 0x00 0x1b 0x00 0x00 0x00
0x7efff1d8: 0x00 0x00 0x00 0x00
Look at the value for year , emphasized here. Note how the least significant byte ( 0xe4 ) comes first. This is due to little-endian data storage, as discussed on page 156 in Project #13 . You can exit gdb with q (it will ask you if you want to quit even though a debugging session is active; answer y ).
PROJECT #15: CHANGE THE TYPE OF VALUE REFERENCED BY A VARIABLE IN PYTHON
Prerequisite: A Raspberry Pi, running Raspberry Pi OS. I recommend that you flip to Appendix B and read the entire “Raspberry Pi” section on page 341 if you haven’t already.
In this project, you'll write code that sets a Python variable to a value of a certain type and then updates that variable to reference a value of a different type. Use the text editor of your choice to create a new file called vartype.py in the root of your home folder. Enter the following Python code into your text editor:
age = 22
print('What is the type?')
print(type(age))
age = 'twenty-two'
print('Now what is the type?')
print(type(age))
This code sets the variable named age to an integer value and then prints the type of that value. It then sets age to a string value and prints the type again.
Once the file is saved, you can run the file from a terminal window using the Python interpreter, like so:
$ python3 vartype.py
You should see output like the following:
What is the type?