HIGH-LEVEL PROGRAMMING**

Image

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 .

image

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 .

image

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 .

image

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.

image

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.

image

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 .

image

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 ).

image

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.

image

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 .

image

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?

Now what is the type? You can see how the type changes from an integer to a string by simply assigning the variable a new value. Don't let the term class confuse you; in Python 3, built-in types such as int and str are considered classes (covered in “Object-Oriented Programming” on page 177 ). Setting a variable to a value of a different type is easy in Python but not allowed at all in C. **_VERSIONS OF PYTHON_** Two major versions of Python are in use today, Python 2 and Python 3. As of January 1, 2020, Python 2 is no longer supported, meaning no new bug fixes will be made to it. Python developers are encouraged to migrate old projects to Python 3, and new projects should target Python 3. Accordingly, the projects in this book use Python 3. On Raspberry Pi OS and some other Linux distributions, running python from a command line will invoke the Python 2 interpreter, while running python3 will invoke the Python 3 interpreter. That’s why the projects in this book have you specifically run python3 rather than python . That said, on other platforms, or even on future versions of Raspberry Pi OS, this may not hold true, and entering python may actually invoke Python 3. You can check the invoked version of Python like so: $ python --version or $ python3 --version **PROJECT #16: STACK OR HEAP** Prerequisite: Project #14 . In this project, you'll look at whether variables are allocated in stack or heap memory in a running program. Open a terminal on your Raspberry Pi, and begin by debugging the vars program you previously compiled in Project #14 : $ 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 continues until the SIGINT statement is executed. (gdb) run Again, look at the memory addresses of the points and year variables. In my case, these variables were found at 0x7efff1d4 and 0x7efff1d0 , but your addresses may vary. Now use the following command to see all the mapped memory locations for your running program: (gdb) info proc mappings The output lists the start and end address of the various memory ranges in use by this program. Find the one that includes the addresses of your variables. Both variable addresses should fall within a single range. For me, this entry matched:     0x7efdf000 0x7f000000   0x21000       0x0 \[stack\] As you can see, gdb indicates that this memory range is allocated for the stack, which is exactly where we would expect local variables to be. You can exit gdb with q (it will ask you if you want to quit even though a debugging session is active; answer y ). Let’s now look at memory allocated on the heap. You need to modify _vars.c_ and rebuild it so that the program allocates some heap memory. Use the text editor of your choice to open the existing _vars.c_ file. Add the following line of code as the very first line: #include Then add these two lines immediately before the SIGINT line: void \* data = malloc(512); printf("data is 0x%08x and is stored at 0x%08x\\n", data, &data); Let’s cover what these changes mean. We call the memory allocation function malloc to allocate 512 bytes of memory from the heap. The malloc function returns the address of the newly allocated memory. That address is stored in a new local variable called data . The program then prints two memory addresses: the address of the new heap allocation and the address of the data variable itself, which should be on the stack. Once the file is saved, use gcc to compile your code: $ gcc -o vars vars.c Now run the program again: $ gdb vars (gdb) run Check the newly printed values. For me, the values are as follows: data is 0x00022410 and is stored at 0x7efff1ac We expect that the first address, the address that came back from malloc , to be on the heap. The second value, the address of the data local variable, should be on the stack. Again, run the following to see this program’s memory ranges and see where these two addresses fall. (gdb) info proc mappings ...            0x22000    0x43000    0x21000        0x0 \[heap\] ...         0x7efdf000 0x7f000000    0x21000        0x0 \[stack\] Find the matching address ranges on your system and confirm that the addresses fall in the expected ranges of heap and stack. You can exit gdb with q . **PROJECT #17: WRITE A GUESSING GAME** In this project, you'll write a guessing game in Python, building on what we’ve covered in this chapter. Use the text editor of your choice to create a new file named _guess.py_ in the root of your home folder. Enter the following Python code into your text editor. In Python, indentation matters, so make sure you indent appropriately. from random import randint ❶ secret = randint(1, 10) ❷ guess = 0 ❸ count = 0 ❹ print('Guess the secret number between 1 and 10') while guess != secret: ❺     guess = int(input()) ❻     count += 1     if guess == secret: ❼         print('You got it! Nice job.')     elif guess < secret:         print('Too low. Try again.')     else:         print('Too high. Try again.') print('You guessed {0} times.'.format(count)) ❽ Let’s examine how this program works. This code starts by importing a function called randint that generates random integers ❶ . This is an example of using a function that was written by someone else; randint is a part of the Python standard library. This call to the randint function returns a random integer in the range of 1 to 10 , which we’ve stored in a variable named secret ❷ . The code then sets a variable called guess to 0 ❸ . This variable holds the player’s guess, and it’s assigned an initial value of 0 , a value we can be sure won’t match the secret value. A third variable named count ❹ keeps track of the number of times that the player guessed so far. The while loop runs as long as the player’s guess doesn’t match the secret ❺ . The code within the loop calls the built-in function input to get the user’s guess from the console ❻ , and the result is converted to an integer and stored in the guess variable. Each time a guess is entered, it’s checked against the secret variable to see whether it’s a match, too low, or too high ❼ . Once the player’s guess matches the secret , the loop exits, and the program prints the number of times that the player guessed ❽ . Once the file is saved, you can run it using the Python interpreter like so: $ python3 guess.py Try out the program several times; the secret number should change each time you run it. You may want to try modifying the program so that the range of allowed integers is larger, or maybe you want to put in your own custom messages. As a challenge, try modifying the program so that when the guess is really close, the program prints a different message. **PROJECT #18: USE A BANK ACCOUNT CLASS IN PYTHON** In this project, you’ll write a bank account class in Python and then create an object based on that class. Use the text editor of your choice to create a new file named _bank.py_ in the root of your home folder. Enter the following Python code into your text editor. You can skip typing in the comments (lines that begin with # ) if you prefer. Note that \_\_init\_\_ has two underscore characters at its beginning and end. \# Define a bank account class in Python. class BankAccount: ❶     def \_\_init\_\_(self, balance, name): ❷         self.balance = balance ❸         self.name = name ❹     def withdraw(self, amount): ❺         self.balance = self.balance - amount     def deposit(self, amount): ❻         self.balance = self.balance + amount \# Create a bank account object based on the class. smithAccount = BankAccount(10.0, 'Harriet Smith') ❼ \# Deposit some additional money to the account. smithAccount.deposit(5.25) ❽ \# Print the account balance. print(smithAccount.balance) ❾ This code defines a new class called BankAccount ❶ . Its \_\_init\_\_ function ❷ is automatically invoked when an instance of the class is created. This function sets instance variables balance ❸ and name ❹ to the values passed into the initializer function. The variables are unique to each object instance of the class that’s created. The class definition also includes two methods: withdraw ❺ and deposit ❻ , which simply modify the balance. After the class is defined, the code proceeds to create an instance of the class ❼ . This bank account object can now be used by accessing its variables and methods. Here a deposit is made ❽ , followed by a retrieval of the new balance, which is printed ❾ . Once the file is saved, you can run it using the Python interpreter like so: $ python3 bank.py You should see the account balance of 15.25 print to the terminal window. In truth, this was an overly complicated way of calculating this bank balance! The numbers are all hard coded in the program, and we really didn’t need to use an object-oriented approach to solve this problem. However, I hope this example helps you understand how classes and objects work. **PROJECT #19: FACTORIAL IN C** Prerequisite: Projects #12 and #13 In this project, you’ll build a factorial program in the C programming language, like the one we covered earlier in this chapter. You’ll then examine the machine code that was generated when the code was compiled. Use the text editor of your choice to create a new file named _fac2.c_ in the root of your home folder. Enter the following C code: #include   // Calculate the factorial of n. int factorial(int n) ❶ {   int result = n;     while(--n > 0)   {     result = result \* n;   }     return result; }   int main() ❷ {   int answer = factorial(4); ❸   printf("%d\\n", answer); ❹ } You can see that the factorial function ❶ is exactly the same as the C example given earlier in the chapter; this is the core code for calculating the factorial. However, to make this a usable program, we also have a main function ❷ that serves as the entry point—this is where the program begins execution. From main , the program calls the factorial function with a value of 4, storing the result in a local variable named answer ❸ . The program then prints the value of answer to the terminal ❹ . Once the file is saved, use gcc to compile your code into an executable file. The following command takes _fac2.c_ as an input and outputs an executable file named _fac2_ . No separate linking step is required. Also note the \-O (that is a capital letter O) command line option: this means enable compiler optimizations. I added this option here because in this case it produces code that’s more similar to the assembly code from Project #12 . $ gcc -O -o fac2 fac2.c Now try running the code using the following command. If everything works as expected, the program should print the calculated result of 24 on the next line. $ ./fac2 Now that you have a fac2 executable file, use the same techniques you used in Projects #12 and #13 to inspect the compiled file. I won’t walk you through all the details again, but the same approaches you used before will work here as well. Here are a few commands to get you started: $ hexdump -C fac2 $ objdump -s fac2 $ objdump -d fac2 $ gdb fac2 You should see right away that there’s a lot of stuff in the fac2 file! The compiled ELF binary carries some overhead required for a program written in C. On my computer, the original fac ELF file was 940 bytes, whereas the fac2 ELF file is 8,364 bytes, a 9X increase! Of course, the C version does include additional functionality to print out the value, so some size increase is expected. When looking at disassembled code, it’s the factorial function you want to initially examine. Compare it to the factorial code that you wrote in assembly language back in Chapter 8 . You may notice gdb shows a different entry point than main . This is because C programs have some initialization code that’s called before your main entry point is called. If you want to skip this code and go right to the factorial function, you can set a breakpoint ( break factorial ) then run , and then disassemble . The machine instructions generated on your machine may differ somewhat, but here’s the factorial function machine code and corresponding assembly language generated on my computer. This is output from objdump -d fac2 : 00010408 :     10408:       e2403001        sub     r3, r0, #1 ❶     1040c:       e3530000        cmp     r3, #0 ❷     10410:       d12fff1e        bxle    lr ❸     10414:       e0000093        mul     r0, r3, r0 ❹     10418:       e2533001        subs    r3, r3, #1 ❺     1041c:       1afffffc        bne     10414 ❻     10420:       e12fff1e        bx      lr ❼ Before this function is called, the value of n has been stored in r0 . When the function begins, right away it decrements n and stores the result in r3 ❶ . The program then compares r3 (that is, n ) to zero ❷ . If n is less than or equal to zero ❸ , then the program returns from the function. Otherwise, result , stored in r0 , is calculated as result × n ❹ . Next n is decremented ❺ , and if n is not zero ❻ , the program goes through the loop again, branching back to address 10414 ❹ . Once n reaches zero, the loop ends and the function returns ❼ .