Preview of C Development
Preview of C Development
C Development
Rob Miles
2008-2009
Computers 12
An Introduction to Computers .......................................................................................... 12
Hardware and Software ...................................................................................... 12
Data and Information ........................................................................................................ 13
Data Processing .................................................................................................. 13
Programmer’s Point:At the bottom there is always hardware ............................. 14
Programming Languages 15
What is Programming? ..................................................................................................... 15
From Problem to Program .................................................................................. 15
Programmer’s Point:The specification must always be there ............................. 16
A Simple Problem ............................................................................................................. 16
Specifying the Problem....................................................................................... 16
Programmer’s Point:metadata is important ......................................................... 17
Programmer’s Point:Good programmers are good communicators .................... 19
Programming Languages .................................................................................................. 19
Programmer’s Point:The language is not that important..................................... 20
C# 20
A look at C# ...................................................................................................................... 20
Dangerous C ....................................................................................................... 20
Programmer’s Point:Computers are always stupid ............................................. 21
Safe C# ............................................................................................................... 21
C# and Objects ................................................................................................... 21
Making C# Run .................................................................................................. 21
Creating C# Programs ........................................................................................ 22
The Human Computer ........................................................................................ 22
Programmer’s Point:Great programmers debug less .......................................... 22
What Comprises a C# Program? ....................................................................................... 22
Controlling the Compiler .................................................................................... 23
Storing the Data .................................................................................................. 23
Describing the Solution ...................................................................................... 23
Identifiers and Keywords .................................................................................... 23
A First C# Program 24
The Program Example ...................................................................................................... 24
using System; ............................................................................................. 24
class GlazerCalc ...................................................................................... 25
static.............................................................................................................. 25
void .................................................................................................................. 25
Main .................................................................................................................. 25
() ....................................................................................................................... 25
i
{ .......................................................................................................................... 26
double.............................................................................................................. 26
width, height, woodLength, glassArea ...................................... 26
Programmer’s Point:Know where your data comes from ................................... 26
; ......................................................................................................................... 26
string widthString, heightString; ............................................. 27
widthString = ............................................................................................. 27
Console. ......................................................................................................... 27
ReadLine ......................................................................................................... 27
() ....................................................................................................................... 27
; ......................................................................................................................... 28
width = ........................................................................................................... 28
double. ........................................................................................................... 28
Parse ................................................................................................................ 28
(widthString); .......................................................................................... 28
heightString = Console.ReadLine(); height =
double.Parse(heightString);............................................................ 29
woodLength = 2*(width + height)*3.25 ; ................................. 29
glassArea = 2 * ( width * height ) ; ...................................... 29
Console.WriteLine ................................................................................... 29
( ......................................................................................................................... 29
"The length of the wood is " ......................................................... 29
+ ......................................................................................................................... 29
woodLength .................................................................................................... 30
+ " feet" ...................................................................................................... 30
) ......................................................................................................................... 30
; ......................................................................................................................... 31
} ......................................................................................................................... 31
} ......................................................................................................................... 31
Programmer’s Point:Program layout is very important ...................................... 31
Punctuation ......................................................................................................... 31
Manipulating Data 32
Variables and Data ............................................................................................................ 32
Types of Variables ............................................................................................................ 32
Storing Numbers ................................................................................................. 32
Storing integer values ......................................................................................... 33
Programmer’s Point:Check your own maths....................................................... 33
integer literal values............................................................................................ 34
Storing real values .............................................................................................. 34
real literal values................................................................................................. 34
Programmer’s Point:Simple variables are probably best .................................... 35
Storing Text ........................................................................................................ 35
char variables ...................................................................................................... 35
char literal values ................................................................................................ 35
string variables.................................................................................................... 36
string literal values.............................................................................................. 37
bool variables ..................................................................................................... 37
bool literal values ............................................................................................... 37
Programmer’s Point:Think about the type of your variables .............................. 37
Identifiers .......................................................................................................................... 38
Programmer’s Point:Think about the names of your variables ........................... 38
Giving Values to Variables ............................................................................................... 39
Expressions ......................................................................................................... 39
Changing the Type of Data ............................................................................................... 40
Widening and Narrowing ................................................................................... 40
Casting ................................................................................................................ 41
ii
Types of Data in Expressions............................................................................................ 42
Programmer’s Point:Casts can add clarity .......................................................... 43
Programs and Patterns ...................................................................................................... 43
Writing a Program 44
Software as a story ............................................................................................................ 44
Comments ........................................................................................................... 45
Programmer’s Point:Don't add too much detail .................................................. 45
Program Flow ................................................................................................................... 45
Conditional Execution - if .................................................................................. 46
Conditions and Relational Operators .................................................................. 46
Combining Logical Operators ............................................................................ 48
Programmer’s Point:Break down your conditions .............................................. 48
Lumping Code Together ..................................................................................... 48
Metadata, Magic Numbers and const ................................................................. 49
Loops ................................................................................................................................ 50
Programmer’s Point:Don't be clever/stupid ........................................................ 53
Breaking Out of Loops ....................................................................................... 53
Programmer’s Point:Be careful with your breaks ............................................... 53
Going back to the top of a loop .......................................................................... 54
More Complicated Decisions ............................................................................. 54
Programmer’s Point:Get used to flipping conditions .......................................... 54
Complete Glazing Program ................................................................................ 54
Operator Shorthand ........................................................................................................... 55
Statements and Values ........................................................................................ 56
Programmer’s Point:Always strive for simplicity ............................................... 57
Neater Printing .................................................................................................................. 57
Using Placeholders in Print Strings .................................................................... 57
Methods 59
Methods So Far ................................................................................................................. 59
Method and Laziness .......................................................................................... 59
Parameters .......................................................................................................... 60
Return values ...................................................................................................... 60
A Useful Method ................................................................................................ 60
Programmer’s Point:Design with methods ......................................................... 61
Method Limitations ............................................................................................ 61
Programmer’s Point:Document your side-effects ............................................... 63
Programmer’s Point:Languages can help programmers...................................... 63
Method Libraries ................................................................................................ 64
Programmer’s Point:Always consider the failure behaviours ............................. 64
Variables and Scope ......................................................................................................... 64
Scope and blocks ................................................................................................ 65
Nested Blocks ..................................................................................................... 65
For loop local variables ...................................................................................... 66
Programmer’s Point:Plan your variable use........................................................ 66
Arrays 66
Why We Need Arrays ....................................................................................................... 66
Array Elements ................................................................................................... 67
Array Element Numbering .................................................................................. 68
Large Arrays ....................................................................................................... 68
Managing Array Sizes ........................................................................................ 68
Creating a Two Dimensional Array .................................................................... 69
More than Two Dimensions ............................................................................... 69
Programmer’s Point:Keep your dimensions low ................................................ 69
iii
Switching 70
Making Multiple Decisions ............................................................................................... 70
Selecting using the if construction.................................................................... 70
The switch construction .................................................................................. 71
Programmer’s Point:switches are a good idea .................................................... 72
Enumerated Types 72
Enumeration and states ..................................................................................................... 73
Sample states ...................................................................................................... 73
Creating an enum type ...................................................................................................... 74
Programmer’s Point:Use enumerated types ........................................................ 74
Structures 75
What is a Structure? .......................................................................................................... 75
A sample structure .............................................................................................. 75
Creating a Structure .......................................................................................................... 76
Using a Structure .............................................................................................................. 76
Initial values in structures ................................................................................... 77
Programmer’s Point:Structures are crucial ......................................................... 77
Enumerated Types in Structures ......................................................................... 77
Static Items 90
Static class members ......................................................................................................... 90
Using a static data member of a class ................................................................. 91
iv
Programmer’s Point:Static Data Members are Useful and Dangerous ............... 92
Using a static method in a class .................................................................... 92
Using member data in static methods ................................................................. 93
Programmer’s Point:Static Method Members can be used to make Libraries .... 94
Bank Notes: Static Bank Information ............................................................................... 94
Inheritance 106
Extending a parent class.................................................................................................. 106
Programmer’s Point:Block Copy is Evil ........................................................... 107
Overriding methods ........................................................................................................ 107
Virtual Methods ................................................................................................ 108
Protection of data in class hierarchies............................................................... 108
Bank Notes: Overriding for Fun and Profit ..................................................................... 109
Using the base method .................................................................................................... 109
Making a Replacement Method ...................................................................................... 110
Programmer’s Point:Don’t Replace Methods ................................................... 110
Stopping Overriding ....................................................................................................... 110
Bank Notes: Protect Your Code ...................................................................................... 111
Constructors and Hierarchies .......................................................................................... 111
Constructor Chaining ........................................................................................ 112
Programmer’s Point:Design your class construction process ........................... 112
Abstract methods and classes .......................................................................................... 112
Abstract classes and interfaces ......................................................................... 113
References to abstract classes ........................................................................... 115
Bank Notes: Designing with interface and abstract......................................................... 115
Don’t Panic ..................................................................................................................... 115
v
The Object class ............................................................................................... 116
The ToString method ................................................................................... 117
Getting the string description of a parent object ............................................... 117
Objects and testing for equals ......................................................................................... 118
Adding an Equals method ................................................................................. 118
Programmer’s Point:Make sure you use the right equals .................................. 119
Objects and this ........................................................................................................... 119
this as a reference to the current instance...................................................... 120
Passing a reference to yourself to other classes ................................................ 120
Confusion with this ....................................................................................... 120
Bank Notes: Good Manners are a Good Idea ................................................................. 120
Programmer’s Point:Always provide an equals behaviour ............................... 121
Properties 124
Properties as class members ............................................................................................ 124
Creating Get and Set methods ......................................................................................... 124
Using Properties.............................................................................................................. 125
Properties and interfaces ................................................................................................. 126
Property problems ........................................................................................................... 126
Property Assignment Failure ............................................................................ 126
Properties Run Code ......................................................................................... 127
Programmer’s Point:Don’t use new fangled stuff just because it is there ......... 127
vi
Interfaces and the save operation ...................................................................... 139
Loading and factories ....................................................................................... 139
Factory Dependencies....................................................................................... 141
Bank Notes: Messy Code ................................................................................................ 141
vii
Using a Class from a Namespace...................................................................... 165
Using a namespace ........................................................................................... 166
Nesting Namespaces ......................................................................................... 166
Namespaces in Separate Files ......................................................................................... 167
Programmer’s Point:Fully Qualified Names are Good ..................................... 167
Debugging 167
Fault Reporting ............................................................................................................... 167
Programmer’s Point:Design Your Fault Reporting Process ............................. 168
The two types of Fault ...................................................................................... 168
Bugswatting .................................................................................................................... 168
Rip it up and start again .................................................................................... 169
Programmer’s Point:Bug Fixes Cause Bugs ..................................................... 170
Making Perfect Software ................................................................................................ 170
viii
Public .............................................................................................................................. 178
Reference ........................................................................................................................ 178
Signature ......................................................................................................................... 178
Source file ....................................................................................................................... 178
Static ............................................................................................................................... 178
Stream ............................................................................................................................. 179
Structure.......................................................................................................................... 179
Subscript ......................................................................................................................... 179
Test harness .................................................................................................................... 179
This ................................................................................................................................. 179
Unit test........................................................................................................................... 179
Value type ....................................................................................................................... 180
Virtual Method................................................................................................................ 180
Index 181
Email: rob@robmiles.com
Blog: www.robmiles.com
ix
Computers Introduction
Introduction
Welcome
Welcome to the Wonderful World of Rob Miles™. This is a world of bad jokes, puns,
and programming. In this book I'm going to give you a smattering of the C#
programming language. If you have programmed before I'd be grateful if you'd still
read the text. It is worth it just for the jokes and you may actually learn something.
If you have not programmed before, do not worry. Programming is not rocket science it
is, well, programming. The bad news about learning to program is that you get hit with
a lot of ideas and concepts at around the same time when you start, and this can be
confusing. The keys to learning programming are:
Practice – do a lot of programming and force yourself to think about things
from a problem solving point of view
Study – look at programs written by other people. You can learn a lot from
studying code which other folk have created. Figuring out how somebody else
did the job is a great starting point for your solution. And remember that in
many cases there is no best solution, just ones which are better in a particular
context, i.e. the fastest, the smallest, the easiest to use etc.
Persistence – writing programs is hard work. And you have to work hard at it.
The principle reason why most folks don't make it as programmers is that they
give up. Not because they are stupid. However, don't get too persistent. If you
haven't solved a programming problem in 30 minutes you should call time out
and seek help. Or at least walk away from the problem and come back to it.
Staying up all night trying to sort out a problem is not a good plan. It just
makes you all irritable in the morning. We will cover what to do when it all
goes wrong later in these notes.
Computers
An Introduction to Computers
Before we consider programming, we are going to consider computers. This is an
important thing to do, because it sets the context in which all the issues of programming
itself are placed.
Qn: Why does a bee hum? One way of describing a computer is as an electric box which humms. This, whilst
Ans: Because it doesn't know technically correct, can lead to significant amounts of confusion, particularly amongst
the words! those who then try to program a fridge. A better way is to describe it as:
Windows XP is an operating All computers are sold with some software. Without it they would just be a novel and
system. It gives computer highly expensive heating system. The software which comes with a computer is often
programs a platform on which called its Operating System. The Operating System makes the machine usable. It
they can execute. looks after all the information held on the computer and provides lots of commands
to allow you to manage things. It also lets you run programs, ones you have written
and ones from other people. You will have to learn to talk to an operating system so
that you can create your C# programs and get them to go.
Data Processing
Computers are data processors. Information is fed into them; they do something with it,
and then generate further information. A computer program tells the computer what to
do with the information coming in. A computer works on data in the same way that a
sausage machine works on meat, something is put in one end, some processing is
performed, and something comes out of the other end:
This makes a computer a very A program is unaware of the data it is processing in the same way that a sausage
good "mistake amplifier", as machine is unaware of what meat is. Put a bicycle into a sausage machine and it will
well as a useful thing to try to make sausages out of it. Put duff data into a computer and it will do equally
blame..... useless things. It is only us people who actually ascribe meaning to data (see above),
as far as the computer is concerned it is just stuff coming in which has to be
manipulated in some way.
A computer program is just a sequence of instructions which tell a computer what to do
with the data coming in and what form the data sent out will have.
Note that the data processing side of computers, which you might think is entirely
reading and writing numbers, is much more than that, examples of typical data
processing applications are:
Digital Watch : A micro-computer in your watch is taking pulses from a crystal
and requests from buttons, processing this data and producing a display which tells you
the time.
Car : A micro-computer in the engine is taking information from sensors telling it the
current engine speed, road speed, oxygen content of the air, setting of the accelerator
etc and producing voltages out which control the setting of the carburettor, timing of
the spark etc, to optimise the performance of the engine.
CD Player : A computer is taking a signal from the disk and converting it into the
sound that you want to hear. At the same time it is keeping the laser head precisely
positioned and also monitoring all the buttons in case you want to select another part of
the disk.
Games Console: A computer is taking instructions from the controllers and using
them to manage the artificial world that it is creating for the person playing the game.
Note that some of these data processing applications are merely applying technology to
existing devices to improve the way they work. However the CD player and games
console could not be made to work without built-in data processing ability.
Most reasonably complex devices contain data processing components to optimise their
performance and some exist only because we can build in intelligence. It is into this
world that we, as software writers are moving. It is important to think of business of
data processing as much more than working out the company payroll, reading in
numbers and printing out results. These are the traditional uses of computers.
Note that this "raises the As software engineers it is inevitable that a great deal of our time will be spent fitting
stakes" in that the data processing components into other devices to drive them. You will not press a
consequences of software switch to make something work, you will press a switch to tell a computer to make it
failing could be very work. These embedded systems will make computer users of everybody, and we will
damaging. have to make sure that they are not even aware that there is a computer in there!
You should also remember that seemingly innocuous programs can have life
threatening possibilities. For example a doctor may use a spreadsheet to calculate doses
of drugs for patients. In this case a defect in the program could result in illness or even
death (note that I don't think that doctors actually do this – but you never know..)
Programming Languages
What is Programming?
I tell people I am a "Software Programming is a black art. It is the kind of thing that you grudgingly admit to doing,
Engineer". at night, with the blinds drawn and nobody watching. Tell people that you program
computers and you will get one of the following responses:
1. A blank stare.
2. "That's interesting", followed by a long description of the double glazing that
they have just had fitted.
3. Asked to solve every computer problem that they have ever had, and ever will
have.
4. A look which indicates that you can't be a very good one as they all drive
Ferraris and tap into the Bank of England at will.
Programming is defined by most people as earning huge sums of money doing
something which nobody can understand.
Programming is defined by me as deriving and expressing a solution to a given
problem in a form which a computer system can understand and execute.
One or two things fall out of this definition:
You need to be able to solve the problem yourself before you can write a
program to do it.
The computer has to be made to understand what you are trying to tell it to do.
And remember just how much I like to think of a programmer as a bit like a plumber! A plumber will arrive at a job
plumbers earn…. with a big bag of tools and spare parts. Having looked at it for a while, tut tutting, he
will open his bag and produce various tools and parts, fit them all together and solve
your problem. Programming is just like this. You are given a problem to solve. You
have at your disposal a big bag of tricks, in this case a programming language. You
look at the problem for a while and work out how to solve it and then fit the bits of
the language together to solve the problem you have got. The art of programming is
knowing which bits you need to take out of your bag of tricks to solve each part of
the problem.
A Simple Problem
Consider the scenario; you are sitting in your favourite chair in the pub contemplating
the universe when you are interrupted in your reverie by a friend of yours who sells
double glazing for a living. He knows you are a programmer of sorts and would like
your help in solving a problem which he has:
He has just started making his own window units and is looking for a program which
will do the costing of the materials for him. He wants to just enter the dimensions of the
window and then get a print out of the cost to make the window, in terms of the amount
of wood and glass required.
"This looks like a nice little earner" you think, and once you have agreed a price you
start work. The first thing you need to do is find out exactly what the customer wants
you to do...
Information going in
In the case of our immortal double glazing problem we can describe the information as:
The width of a window.
The height of the window.
Height of
Window
Width of Window
The area of the glass is the width multiplied by the height. To make the frame we will
need two pieces of wood the width of the window, and two pieces of wood the height of
the window.
The width of the window, in metres and being a value between 0.5 Metres
and 3.5 metres inclusive.
The height of the window, in metres and being a value between 0.5 metres
and 2.0 metres inclusive.
Note that we have also added units to our description, this is very important - perhaps
our customer buys wood from a supplier who sells by the foot, in which case our output
description should read :
The area of glass required for the window, in square metres. Remember
that we are selling double glazing, so two panes will be required.
The length of wood required for the frame, given in feet using the
conversion factor of 3.25 feet per metre.
Note that both you and the Having written this all up in a form that both you and the customer can understand,
customer must understand we must then both sign the completed specification, and work can commence.
the document!
Proving it Works
In a real world you would now create a test which will allow you to prove that the
program works, you could for example say:
If I give the above program the inputs 2 metres high and 1 metre wide the program
should print out: 4 square metres of glass and 9.75 feet of wood.
The test procedure which is designed for a proper project should test out all possible
states within the program, including the all important error conditions. In a large system
the person writing the program may have to create a test harness which is fitted around
the program and will allow it to be tested. Both the customer and the supplier should
agree on the number and type of the tests to be performed and then sign a document
describing these.
Testing is a very important part of program development. There is even one
development technique where you write the tests before you write the actual program
that does the job. This is actually a good idea, and one we will explore later. In terms of
code production, you can expect to write as much code to test your solution as is in the
solution itself. Remember this when you are working out how much work is involved in
a particular job.
Getting Paid
Better yet, set up a phased At this point the supplier knows that if a system is created which will pass all the tests
payment system so that you the customer will have no option but to pay for the work! Note also that because the
get some money as the system design and test procedures have been frozen, there is no ambiguity which can lead to
is developed. the customer requesting changes to the work although of course this can still happen!
The good news for the developer is that if changes are requested these can be viewed in
the context of additional work, for which they can be expect to be paid.
Customer Involvement
Note also in a "proper" system the customer will expect to be consulted as to how the
program will interact with the user, sometimes even down to the colour of the letters on
the display! Remember that one of the most dangerous things that a programmer can
think is "This is what he wants"! The precise interaction with the user - what the
program does when an error is encountered, how the information is presented etc., is
something which the customer is guaranteed to have strong opinions about. Ideally all
this information should be put into the specification, which should include layouts of
the screens and details of which keys should be pressed at each stage. Quite often
prototypes will be used to get a idea of how the program should look and feel.
Fact: If you expect to derive If this seems that you are getting the customer to help you write the program then you
the specification as the are exactly right! Your customer may have expected you to take the description of the
project goes on either you will problem and go into your back room - to emerge later with the perfect solution to the
fail to do the job, or you will problem. This is not going to happen. What will happen is that you will come up with
end up performing five times something which is about 60% right. The customer will tell you which bits look OK
the work! and which bits need to be changed. You then go back into your back room, muttering
under your breath, and emerge with another system to be approved. Again, Rob's law
says that 60% of the duff 40% will now be OK, so you accept changes for the last
little bit and again retreat to your keyboard....
The customer thinks that this is great, reminiscent of a posh tailor who produces the
perfect fit after numerous alterations. All the customer does is look at something,
suggests changes and then wait for the next version to find something wrong with. They
will get a bit upset when the delivery deadline goes by without a finished product
appearing but they can always cheer themselves up again by suing you.
Fact: More implementations If your insistence on a cast iron specification forces the customer to think about
fail because of inadequate exactly what the system is supposed to do and how it will work, all to the better. The
specification than for any customer may well say "But I am paying you to be the computer expert, I know
other reason! nothing about these machines". This is no excuse. Explain the benefits of "Right First
Time" technology and if that doesn't work produce a revolver and force the issue!
Again, if I could underline in red I would: All the above apply if you are writing the
program for yourself. You are your own worst customer!
You may think that I am labouring a point here; the kind of simple systems we are
going to create as we learn to program are going to be so trivial that the above
techniques are far too long winded. You are wrong. One very good reason for doing
this kind of thing is that it gets most of the program written for you - often with the help
of the customer. When we start with our double glazing program we now know that we
have to:
read in the width
verify the value
read in the height
verify the value
calculate width times height times 2 and print it
calculate ( width + height ) * 2 * 3.35 and print it
The programming portion of the job is now simply converting the above description
into a language which can be used in a computer.......
Programming Languages
Once we know what the program should do (specification), and how we are going to
determine whether it has worked or not (test) we now need to express our program in a
form that the computer can work with.
You might ask the question "Why do we need programming languages, why can we not
use something like English?" There are two answers to this one: