Main

Lecture 6

Today we will introduce a couple of C concepts (function pointers and typedefs) and then interact with the OS with Bash scripts.

1. C typedefs

Last time we defined some C structs, including Point, but every time we wanted to use it to declare a variable or a function argument, we had to specify the type as struct Point. Why not just Point?

In C (and C++), users can specify new types by using typedef. These types are called user-defined types, as opposed to the basic types provided by the language.

We can declare a type for the Point structure in one of the following ways.

  1. typedef struct {
  2.   int x, y;
  3. } Point;

Or the following syntax would also work:

  1. struct PointStruct {
  2.   int x, y;
  3. };
  4. typedef struct PointStruct Point;

Now we no longer use "struct" when declaring variables of type Point, for example:

  1. Point x;
  2. void movePoint_wrong(Point p, const int dist);
  3. void movePoint(Point *p, const int dist);
  4. void printPoint(Point p);

2. C function pointers

So far we have only considered pointers to variables. In C you can point to functions, too, for example, fptr below is a pointer to a function. You can assign to it any function that has a matching prototype (return type and list of arguments):

double (*fptr) (double x[]);

You must initialize the pointer (i.e., assign a function to it) before you can call it. For example:

  1. double (*fptr) (double x[]);
  2.  
  3. double computeAverage(double y[]) {
  4.    //...
  5. }
  6.  
  7. int main() {
  8.   double x = {1.0,2.0,3.0};
  9.   double avg = 0.0;
  10.  
  11.   fptr = &computeAverage;
  12.   avg = fptr(x);
  13.   printf("Average: %f\n", avg);
  14. }

Why are function pointers useful? They can be used to enable callbacks -- i.e., have a certain function be called when some event occurs, or to pass functions as arguments of functions, enabling more flexible implementations.

Here is an example of an array of function pointers.

Many more examples of function pointers can be found here.

3. Unix shell programming

Reference: Getting started with bash

  • Before we get serious
  • Bourne shell (sh) is a shell, or command-line interpreter, for computer operating systems. It was developed by Stephen Bourne at Bell Labs and released in 1977.
  • Bash (the Bourne-Again shell) was later developed for the GNU project. Bash incorporates features from the Bourne shell, csh, and ksh.
  • Bash Introduction (also see schedule)
  • Important concepts:
    • Variables: environment and local
    • Input and output redirection
    • Pipes
    • Signals
    • Operators
    • Control flow (conditionals, loops)
  • Examples

Hello world script in Bash

Reference: Bash hello world

Green Marinee theme adapted by David Gilbert, powered by PmWiki