StartingC

From SourceWiki
Jump to navigation Jump to search

startingC: Learning the C Programming Language

Introduction

svn co http://source.ggy.bris.ac.uk/subversion-open/startingC/trunk ./startingC

A Quintessential First Program

OK, now that we have the example code, let's get cracking and run our first C program. First of all, move into the example directory:

cd startingC/examples/example1

We'll use of a Makefile for each example, so as to make the build process painless (hopefully!). All we need do is run make (see the [make tutorial about make] if you're interested in this further):

make

Now, we can run the classic program:

./hello.exe

and you should get the friendly response:

hello, world!

Bingo! We've just surmounted--in some ways--our hardest step; running our first C program. Given this quantum leap, everything else will be plain sailing from here, honest!

Types & Operations

Buoyed with confidence from our first example, let's march fearlessly onwards into the realm of variable types and basic operations. To do this, move up and over to the directory example2 and type make to build the example programs:

cd ../example2
make

Take a look inside types.c and after the start of the main function, you'll see a block of variable declarations:

  char   nucleotide;        /* A, C, G or T for our DNA */
  int    numPlanets;        /* eight in our solar system - poor old Pluto! */
  float  length;            /* e.g.  1.8288m, for a 6' snooker table */
  double accum;             /* an accumulator */

C, like many languages (e.g. Fortran), requires that variables must be declared to be of a certain type before they can be used, and here we see examples of four intrinsic types provided by the language. It's a very good habit to comment all your variable declarations, and here the comments pretty much explain what the various types are. double is a double precision--twice the storage space of a float--floating point number. The extra space make a double a good choice for an accumulator where you want to minimise rounding errors and avoid under- and overflow as best as possible. (The Fortran programmers amongst us will note, with a whince, the absence of an implicit type for complex numbers. Those reeling from this revelation will be comforted by the knowledge that C++ contains a complex class.)

Various types can be given further qualifiers, such as short, long, signed and unsigned:

  short int mini;           /* typically two bytes */ 
  long  int maxi;           /* typically eight bytes */ 
  signed char cSigned;      /* one byte, values in the range [-128:127] */
  unsigned char cUsigned;   /* values in the range [0:255] */

The const keyword is also very useful for, well, declaring constants. In invaluable intrinsic (aka built-in) function when pondering the amount of memory assigned to a variable is sizeof().

In addition to single entities of various types, we can also declare arrays of the self-same intrinsics. The syntax for this is along the lines of:

  char cStr[20];            /* a character array/string of 20 chars */
  int  iMat2d[3][3];        /* a 2-dimensional matrix of integers - 3x3 */

You'll see a good deal more of accessing the various elements of an array in later examples, but for now be satisfied with the knowledge that array indices start at 0 in C (yes, that's right Fortraners, that's zero, not 1) and that the syntax for array access is, e.g.:

cStr[0] = 'h';  /* first elememt set to ascii char code for 'h' */

Enumerated types can be a useful way to map (a list of) symbolic names to integer values.

Now that you've read it through, run the program and satisfy yourself that it all works as you expect it to.


Shifting our attention to operations.c, let's consider some basic operations that C supports. This is the start of the doing things part.

The first block of code here gives an arithmetic example--how to calculate the volume of an oblate spheroid that happens to be close to all our hearts, our shared home Earth:

val = (4.0/3.0) * pi * pow(equi_rad,2) * pol_rad;

I won't dwell on this as I'm confident that the syntax is self-explanatory, save to mention that the function pow comes from the built-in library of math functions.

Next up, you'll see the decrement and increment operators:

  --numPlanets;
  ++numPlanets;

also self-explanatory.

C provides the logic operators, == (is equal), != (not equal), && (AND) and || (OR); as well as the relationals, > (greater than), '< (less than), >= (greater than or equal) and <= (less than or equal).

casting

Now, it's very important that you muck around with these example programs as much as possible! Ideally, so much so that you break them! We never learn as much as when we make a mess of things, and since these are just toy programs, you may as well go for it! If you get in a pickle, you can get the original programs back with a quick waft of the Subversion wand:

svn revert *

Exercises

types.c

  • do this
  • then that

operations.c

  • this
  • that

The C Preprocessor

Loops & Conditionals

if then else

(switch) case (default - fall through)

while and for

break & continue

Functions & Header Files

Arrays & Pointers

address, dereference address arith 2d arrays binary trees and linked lists - just give examples

Structures

DAB again

watch out for padding

The Command Line and I/O

Further Reading

The bible is The C Programming Language by Kernighan & Ritchie.