programming for msc part i - little red-haired...
TRANSCRIPT
Programming for MSc Part I
Herbert Martin Dietze∗
University of Buckingham
July 24, 2001
AbstractThe course introduces the C programming language
and fundamental software development techniques.
These lectue notes by no means cover the course
contents as they are merely intended to support the
lecture.
∗Thanks to Prof. Dr. Uwe Schmidt for teaching me C and giving me a lot of inspiration
Programming for MSc Part I July 24, 2001
Contents
1. Fundamentals
(a) Programming Language Elements
(b) Compiling, Linking and Running Programs
(c) C Language Elements
(d) Branching
2. Scalar Data Types
(a) What Scalar Types are
(b) Operations on Scalar Types
(c) Introduction to Boolean Algebra
(d) Enumerations
(e) Defining own Types
(f) Pointers
(g) Increment and Decrement
3. Aggregate Data Types
(a) Arrays
(b) Structs
4. Control Flow
(a) Loops
(b) Advanced Branching
5. Dynamic Data structures
(a) Allocating and Releasing Memory
(b) List Structures
6. The Preprocessor and Macros
Herbert Martin Dietze <[email protected]> 1
Programming for MSc Part I July 24, 2001
(a) The Preprocessors
(b) Macros
Herbert Martin Dietze <[email protected]> 2
Programming for MSc Part I Part 1: Fundamentals
(a) Programming Language Elements
Computers and Humans
• Humans can use intuition to solve problems
• The computer only executes a sequences of instructions
• Simple operations (addition, comparison), but high speed
• Questions: Which instructions and in what order?
• Describe rules to solve a problem −→ Algorithm
• Simple examples: A cooking recipe, or x2 = x ∗ x
• A computer can’t understand an algorithm without our help
• Not every algorithm can be made a computer program
Computer Programs and Programming Languages
• A Computer Program can be executed on a computer
• A computer program implements an algorithm
• The computer program is written in a Programming Language
• The programmer creates a Source File
• Then a special computer program, the Compiler is invoked
• The Compiler generates machine code from the source file
• Every processor type uses its own machine language
Herbert Martin Dietze <[email protected]> 3
Programming for MSc Part I Part 1: Fundamentals — Programming Language Elements
Low and High Level Programming Languages
• We call low level programming languages Assembly Languages
• Assembly language is a processor’s language’s readable form
• Primitive instructions, very close to the processor
• High level programming languages are processor independent
• More complex instructions, high abstraction level
• Some high level programming languages: Pascal, C, C++, ...
The C Programming Language
• Developed in the early seventies for the Unix operating system
• Later: ANSI standard
• Operating systems written in C: Windows, Unix, OS/2, ...
• Popular general purpose programming language
• Small set of instructions, relatively little abstraction
Example C Source
Source file fiveptwo.c :
intmain (void){5*5;return 0;
}
Herbert Martin Dietze <[email protected]> 4
Programming for MSc Part I Part 1: Fundamentals — Programming Language Elements
Human Languages Analogy
• A programming language is just a language
• It consists of Characters, Words and Sentences
• We call them Tokens, Expressions and Statements
Tokens
• A token is the smallest unit C can handle −→ “Atom”
• Expressions consist of one or more tokens
• Examples:
Text C Tokens
hugo hugo42 426*9 6, *, 9
(4+2)*9 (, 4, +, 2, ), *, 9
• The compiler will always form the longest-possible token
• To avoid ambiguity rules for creating tokens are needed
Expressions
• Expressions are what sentences are made of
• They can be just constants: 42
• Operators can make expressions more complex: 6*9
• Every expression has a value
Herbert Martin Dietze <[email protected]> 5
Programming for MSc Part I Part 1: Fundamentals — Programming Language Elements
Statements
• A statement (“sentence”) is a command we want to execute
• It ends with a semicolon “;” or a closing brace “}”• An Empty statement contains nothing: ;
• An Expression statement consist of one expression: 5*5;
• A Compound statement bundles many to one: {5*5; 6*6;}• There are some more categories of statements
Example
Let’s take another look at fiveptwo.c :
intmain (void){5*5;return 0;
}
• A list of two statements between “{” and “}”• That consist of expressions: 5*5 and return 0
• That consist of tokens: {, 5, *, 5, ;, return, 0, ;, }• And some stuff we don’t know yet
Herbert Martin Dietze <[email protected]> 6
Programming for MSc Part I Part 1: Fundamentals
(b) Compiling, Linking and Running Programs
From the Source to an Executable Program
• The compiler compiles every file to machine language
• The result is one Object File for every source file
• The Linker bundles object files to an executable file
• The executable file can only be run on the target platform
ExecutableProgram
?
?
.oFile
?
cc
.cFile
?
.oFile
?
cc
.cFile
?
.oFile
?
cc
.cFile
?
.oFile
?
cc
.cFile
�ld Library
Herbert Martin Dietze <[email protected]> 7
Programming for MSc Part IPart 1: Fundamentals — Compiling, Linking and Running Programs
What a Program can do
• Technically a program only pushes 1s and 0s around
• From a our point of view it talks with the operating system
• Several categories of operations
• Input — read something from a file or the keyboard
• Output — write something to a file or the screen
• Arithmetics — calculate something
• Data manipulation — e.g. text, images etc.
• Operating systems and toolkits provide help for complex
tasks:
– GUI windows
– Database access
– etc.
These operations come in Libraries
−→ We don’t want to reinvent the wheel!
The C standard library
• The C language itself is rather primitive
• The C standard library is the standard toolkit for C programs
• It provides things like high mathematics (e.g. trigonometric
functions), input and output etc.
• The linker will search the standard library automatically
−→ No useful C program without using the standard library
Herbert Martin Dietze <[email protected]> 8
Programming for MSc Part IPart 1: Fundamentals — Compiling, Linking and Running Programs
A closer Look at the Compiler
• Compiling a C source involves two steps:
1. The Preprocessor expands Preprocessing directives that
can be used to create macros or include other source files
2. The Compiler analyzes the result and generates machine
code from it if there were no errors
• Source files that are not syntactically correct will be rejected
• Object files are no complete executable files!
The Linker
• The linker bundles code from object files and libraries
• It also adds things needed by the operating system
• Complex programs consist of many modules
• The linker resolves dependencies
Running an Executable File
• The operating system loads the program code into memory
• In every program there must be a entry point for execution
• The operating system now jumps to that entry point and
starts executing instruction by instruction
• In a C program execution starts at main ()
Herbert Martin Dietze <[email protected]> 9
Programming for MSc Part IPart 1: Fundamentals — Compiling, Linking and Running Programs
C in the Unix Enviroment
• On Unix systems the compiler for C sources is cc (or gcc)
• The linker is ld
• The Linker normally gets invoked by the compiler
The following commands compile and link the source fiveptwo.c
to creae an executable file fiveptwo:
herbert@paola:~/src $ gcc -c fiveptwo.cherbert@paola:~/src $ gcc -o fiveptwo fiveptwo.oherbert@paola:~/src $ _
Or all in one command:
herbert@paola:~/src $ gcc -o fiveptwo fiveptwo.cherbert@paola:~/src $ _
We can now run the program:
herbert@paola:~/src $ ./fiveptwoherbert@paola:~/src $ _
−→ Does it do anything at all???
Herbert Martin Dietze <[email protected]> 10
Programming for MSc Part IPart 1: Fundamentals — Compiling, Linking and Running Programs
So what’s 5*5 now?
• fiveptwo calculates fine, but how do we know the result?
• Solution: We need to output the result
• We therefore have to extend our source:
#include <stdio.h>intmain (void){
printf ("%d\n", 5*5);return 0;
}
• printf () is a utility from the Standard C Library
• It outputs text to the screen
• The #include statement is an instruction to the preprocessor
Now we can see the result:
herbert@paola:~/src $ gcc -o fiveptwo fiveptwo.cherbert@paola:~/src $ ./fiveptwo25herbert@paola:~/src $ _
Herbert Martin Dietze <[email protected]> 11
Programming for MSc Part I Part 1: Fundamentals
(c) C Language Elements
Syntax
• Like a human language there are a set of rules
• The compiler can only work on syntactically correct sources
• Some rules:
– Statements end with semicolons or a closing braces
– There is a set of operators
– There is a set of reserved keywords
• On syntax errors the compiler will issue an error message
Example for a syntax error in source file foo.c (does not end with
semicolon or closing brace):
#include <stdio.h>intmain (void){printf ("Hello World.\n")return 0;
}
herbert@paola:~/src $ gcc -c foo.cfoo.c: In function ‘main’:foo.c:6: parse error before ‘return’herbert@paola:~/src $ _
Herbert Martin Dietze <[email protected]> 12
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Types
• Any kind of data in C has a type
• A type is a name for a category of data
• C has a list of builtin types (e.g. int for integer numbers or
char for characters)
−→ You can’t compare apples and oranges!
Functions
• A function calculates something and returns the result
• We already know functions: Entering a number and then
pressing the sin key on a pocket calculator
• In C a Function Definition looks like this:
Return-Type Name (Arguments) Compound-Statement
• Between all those elements we can have any number of
whitespaces (tabulators, newlines etc.)
Example:
intanswer (void){
return 6*9-12;}
Herbert Martin Dietze <[email protected]> 13
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Definitions vs. Declarations
• A complete function with body is called Function Definition
• There can be only one definition of the same function
• A function declaration looks like this:
Return-Type Name (Arguments);
• The same funtion can be declared more than once
• Important: The compiler uses them to check the way we call
the functions
• If missing: a function returning int is assumed
• Function declarations are also called Function Prototypes
• Definition and declaration must be consistent
Header Files
• Header files are usually #include’d by the preprocessor
• They contain declarations of all kinds: function prototypes,
types, macros
• System headers are included by #include <headername.h>
• For our own headers we use #include "headername.h"
• Example: #include <stdio.h> for printf() and friends
−→ Header Files are the glue between modules in C
Herbert Martin Dietze <[email protected]> 14
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Variables
• A variable is an object in memory that can store data
• Values are assigned using the assignment operator “=”
• Example: Output the results of 6 ∗ 9 and 6 ∗ 9− 12
• Inefficient solution:
printf ("%d\n", 6*9);printf ("%d\n", 6*9-12);
• Better: Store the result of 6 ∗ 9 in a variable, output it, then
calculate on and output the second result:
int result;result = 6*9;printf ("%d\n", result);result = result - 12;printf ("%d\n", result);
Creating Variables
• There are different kinds of variable declarations
• The simplest form is:
Type Name;
• We can also create more than one variable: int a, b;
• This can only be done at the start of a Compound Statement
or outside functions
Herbert Martin Dietze <[email protected]> 15
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Variables Properties
• A variable is identified by its name
• A variable must be given a type
• Name and type chosen for a variable must be legal
• A variable must have been declared before use
• Values assigned to variables must be of compatible types
• After creation a variable has a random value
Global and Local Variables
• Variables defined in compound statements are local
• They are invisible outside their block
• Variables defined outside compound statements are global
• They are visible through the whole source file
• Global variables should not be used −→ side effects
Example:
int global;
intfoo (void){int local = global;return local;
}
Herbert Martin Dietze <[email protected]> 16
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Function Arguments
• Function arguments are a special kind of variables
• They get initialized when the function is called
• They are ordinary local variables to their function
Example:
#include <stdio.h>
int plustwo (int value);
intmain (void){int fourty = 40;printf ("%d + 2 is %d\n",
fourty, plustwo (fourty));return 0;
}
intplustwo (int value){return value + 2;
}
Herbert Martin Dietze <[email protected]> 17
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Comments
• Comments are used to document source code
• They get ignored by the compiler
• Comments are all between “/*” and “*/”
• It is good style to comment function heads or blocks
• Nesting comments (/* /* ... */ */) does not work!
• There are a lot of different ways to format comments
−→ Matter of taste!
Example:
/** This function adds 2 to ‘value’ and* returns the result*/
intanother_plustwo (int value){/* using the previous one-liner is more
elegant, still this works well, too! */value = value + 2;return value;
}
Herbert Martin Dietze <[email protected]> 18
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Names
• Names are used e.g. for functions or variables
• They can be almost freely chosen, but:
– C’s builtin keywords are reserved
– They’re not allowed to start with numbers
– They’re not allowed to contain any special characters but
the underscore “ ”
– Names starting with “ ” are reserved for system use
• There can be only one sybol of name name in one block
Names Examples:
legal• j• j5• system name• CaPiTaLS oR NoT
illegal• 5J• $name• int• bad%$&name
Herbert Martin Dietze <[email protected]> 19
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Reserved Words
These words are reserved by the C language:
auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while
Basic Input and Output
• The printf() utility performs formatted output
• Example: printf ("A number: %d\n", 42)
• The scanf() utility performs formatted input
• Input must be written to a variable’s address
• We get a variable’s address using the “&” operator
• The Format string is mostly like in printf()
• Normally only the placeholders are needed
• Example: scanf ("%d", &var)
But what if the user does not enter an integer?
• scanf() does not help us here!
−→ More sophisticated methods will come later!
Herbert Martin Dietze <[email protected]> 20
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Example using ‘printf’ and ‘scanf’
#include <stdio.h>
int getnum (void);
/* main program: get input and display* the result. */
intmain (void){int value = getnum ();printf ("That was %d\n", value);return 0;
}
/* Prompt the user for an integer number* and return the result. No checks for* valid input format are performed. */
intgetnum (void){int num;printf ("Enter integer number!\n");scanf ("%d", &num);return num;
}
Herbert Martin Dietze <[email protected]> 21
Programming for MSc Part I Part 1: Fundamentals — C Language Elements
Simple Arithmetics and Logical Expressions
For integer numbers there are several arithmetic operators:
a + b adds a to ba - b subtracts b from aa * b multiplies a by ba / b divides a by b discarding the rest
a % b returns the rest of the division a by b
Comparing expressions:
a == b a equals b (not the same as ‘a = b’ !)a != b a does not equal ba > b a is greater than ba < b a is less than ba >= b a is greater or equal to ba <= b a is less or equal to b
Combining expressions:
expr1 && expr2 expr1 and expr2 are both true
expr1 || expr2 At least expr1 or expr2 is true
!expr The opposite of expr
• In C logical expressions are of the type int
• A false condition resolves to 0
• A true condition resolves to something not equal to 0
Herbert Martin Dietze <[email protected]> 22