Computation

es.ele.tue.nl

Computation

Computation

5JJ70

‘Implementatie van rekenprocessen’

Expression and statements

Henk Corporaal

September 2009

1


Welcome back!

• Last time:

– First encounter with C.

– Bi Binary number b encoding, di two’s ’ complement l

– if(), printf(), scanf().

– Some irritating syntax issues

•Today:

– More useful functions

– Good coding practices

– Expressions and assignments

– Logical functions and operations

–Material:

• Lipman: 2.1-2,4, 2.7, 5.1-5.5, 6.1-6.6

• Ammeraal: Chapter 2 (except 2.5), Chapter 3

• Kernighan & Ritchie 12 1.2, 21 2.1, 22 2.2 23 2.3 25 2.5 26 2.6 28 2.8 29 2.9 210 2.10 211 2.11

© PG/HC 2007 Computation 5JJ70 pg 2


Compiled and Interpreted languages

• C and C++ are languages that must be compiled, that is, translated

into machine code through an elaborate process:

#include

void main()

{

printf(“Hello kids\n”);

}

C Pre-

processor compile Object file

Object task1 task1.obj file obj

Source file

task1.c

Object task1.obj file

Object task1.obj file

task1.obj

linker

Exe-

cutable bl

• Other languages are ‘interpreted’. This means that the source text is

read line-by-line and executed immediately. Examples: Basic, Matlab,

TCL, HTML, Perl, PostScript, APL, csh,

10 rem my program

20 a = a+ 1

30 if a < 100 goto g 20

40 print ready

interpreter

•Advantages:

– Simple and interactive

• Disadvantages:

Disadvantages

– Slow: each statement has to be

translated many times

–No global optimizations

© PG/HC 2007 Computation 5JJ70 pg 3


The compile mechanism

• The hardware (CPU) runs machine instructions only

–it does not run the C-source text

•A compiler p generates g the machine instructions.

• The output of the compiler is object code that is specific for a

particular hardware platform (e.g. Pentium, or PowerPC, MIPS)

#include

void main()

{

printf(“Hello kids\n”);

}

Source file

Task1 Task1.c

c

error

CPre C Preprocessor

compile

Object file

Task1.obj

© PG/HC 2007 Computation 5JJ70 pg 4


Linking it together

• The ‘linker’ puts assembles compiled pieces of code together to make

an executable.

– It picks the necessary routines, calculates the proper

addresses, dd and d ti ties it t to lib libraries i (dll’s) ( ’)

• BUT.. The system needs to know what is to be linked, and which

source files must be used.

• In unix/linux unix/linux, ‘makefiles’ makefiles are used to t maintain dependencies and call

the linker program with the proper options.

• Visual C++ has the notion of a ‘project’:

Object

file(s)

(binary)

link

executable

This is the one

You can actually run!

Task1.exe

© PG/HC 2007 Computation 5JJ70 pg 5


The genesis of C

Ken Thompson, (Dennis Ritchie and Brian Kernighan):

"In 1969, AT&T had just terminated their work with the GE/Honeywell/AT&T

Multics Mult cs project. Br Brian an and I had just started work working ng wwith th an early release of

Pascal from Professor Nicklaus Wirth's ETH labs in Switzerland and we were

impressed with its elegant simplicity and power. Dennis had just finished

reading Bored of the Rings, a hilarious National Lampoon parody of the

great r t Tolkien T lki n LLord rd of f th the Rin Rings s tril trilogy. As a llark, rk we ddecided cid d t to d do pparodies r di s

of the Multics environment and Pascal. Dennis and I were responsible for the

operating environment. We looked at Multics and designed the new system to

be as complex p and cryptic yp as possible p to maximize casual users' frustration

levels, calling it Unix as a parody of Multics, as well as other more risque

allusions. Then Dennis and Brian worked on a truly warped version of Pascal,

called 'A'. When we found others were actually trying to create real

programs with A A, we quickly added additional cryptic features and evolved

into B, BCPL and finally C. We stopped when we got a clean compile on the

following syntax:

for(;P("\n"),R--;P("|"))for(e=C;e--;P("_"+(*u++/8)%2))P("| "+(*u/4)%2);

© PG/HC 2007 Computation 5JJ70 pg 6


The genesis of C (continued)

"To think that modern programmers would try to use a language that

allowed such a statement was beyond our comprehension! We

actually t ll th thought ht of f selling lli this thi to t the th Soviets S i t to t set t their th i

computer science progress back 20 or more years.

Imagine m g our surprise p when AT&T and other US corporations p actually y

began trying to use Unix and C! It took them 20 years to develop

enough expertise to generate even marginally useful applications

using this 1960's technological parody, but we are impressed with

the tenacity (if not common sense) of the general Unix and C

programmer.

In any y event, Brian, Dennis and I have been working g exclusively y in

Ada on the Apple Macintosh for the past few years and feel really

guilty about the chaos, confusion and truly bad programming that

have resulted from our silly prank so long ago."

© PG/HC 2007 Computation 5JJ70 pg 7


Some general programming languages

• Ada US dept. of Defense, descended from Pascal

•APL “AProgramming Language”.

• Algol 60/68 “Algorithmic Language”

• Assembly Machine language

•Basic “Beginner's All Purpose Symbolic Instruction Code”

• Cobol Common Business Orientend Language

• C++ Object-oriented C.

• Fortran “Formula Formula Translation” Translation The dinosaur is still alive!

• Java After the favorite drink of programmers.

•Lisp “List Processing language” (or... Lots of Irritating

Superfluous Parentheses)

•Pascal (Blaise ( Pascal). ) Developed p by y Niklaus Wirth

Interpreted languages:

• AWK after the initials of its inventors: Aho, Weinberger,

Kernighan g

•Perl “Practical Extraction and Report Language“

•TCL “Tool Control Language”

• Basic, Matlab, etc.

See http://shootout.alioth.debian.org/

for benchmarking programming languages

© PG/HC 2007 Computation 5JJ70 pg 8


C drawbacks

•This is no the easiest language to learn.

• It allows many y ways y to shoot yourself y in the foot.

• Poor programmers can produce very messy code.

• Poor support for object oriented programming.

© PG/HC 2007 Computation 5JJ70 pg 9


C++ : an improved C

• C++ is a superset of C: everything in

C is also in C++.

• C++ supports:

– Better data abstraction

– object-oriented programming

– generic programming

• But C++ is mighty difficult to master.

• Stroustrup’s Stroustrup s books (too the right)

explains C++ in detail. Unfortunately,

they are not good course books.

© PG/HC 2007 Computation 5JJ70 pg 10


• Edsger Wybe Dijkstra

Programming in Eindhoven

• Born 1930, died August 8th ,

2002 in Nuenen.

• Professor in Eindhoven

f from 1962 until til 1982

• Won ‘Turing award’ in 1972.

•World ld f famous for: f

– Shortest path algorithm

– ‘Dining philosophers problem’

– Semaphores (to protect critical sections)

– Structured programming paradigms that

led to ALGOL and modern programming

languages (such as C) C).

Notice: no

computer on

his desk!!

© PG/HC 2007 Computation 5JJ70 pg 11


Quotes from Dijkstra

• “Goto statement considered harmful” (Communications ( Communications of the ACM, Vol. 11, No. 3,

March 1968, pp. 147-148.) 147 148.)

• “It is i practically ti ll impossible i ibl to t teach t h good d programming i style t l to t

students that have had prior exposure to BASIC: as potential

programmers they are mentally mutilated beyond hope of

regeneration

regeneration.” .”

• "The use of COBOL cripples the mind; its teaching should, therefore,

be regarded as a criminal offense".

• "Program "P "Program m t testing stin can n b best st sh show th the p presence s n of f errors s b but t n never

their absence"

• "The competent programmer is fully aware of the strictly limited size

of f his his own n skull; skull; therefore th f he h approaches pp ch s the th programming p mmin task t sk in in full

full

humility, and among other things he avoids clever tricks like the

plague" (from 1972 Turing Award Lecture)

• "I mean, mean if 10 years from now now, when you are doin doing something somethin quick and

dirty, you suddenly visualize that I am looking over your shoulders and

say to yourself, "Dijkstra would not have liked this", well that would

be enough immortality for me"

© PG/HC 2007 Computation 5JJ70 pg 12


Machine language structure

CPU

(e.g. pentium)

Instruction fetch

Address

( 32 bit)

034550 instr.

034554 instr.

034558 instr.




035600 instr.

© PG/HC 2007 Computation 5JJ70 pg 13


These are the

actual Pentium

machine m instructions.

It is binary, shown as

hexadecimal.

Th These are the th memory

addresses of the instructions

(a 32-bit

binary y number, , shown

hexadecimal)

This is the

interpretation of the

binary instruction on

the left. This is called

disassembly. y (fdiv

Two numbers)

Looking at object code

• The CPU-view shows the machine code and the source code:

© PG/HC 2007 Computation 5JJ70 pg 14


Conditional structures: if() and switch()

char direction = ‘e’;

/* somewhere set direction */

char opposite_direction;

switch switch(direction) {

case ‘n’: /* north */

opposite_direction = ‘s’;

break;

case ‘w’: /* west */

opposite_direction = ‘e’;

break;

case ‘s’: /* south */

opposite opposite_direction direction = ‘n’; n ;

break;

case ‘e’: /* east */

opposite_direction = ‘w’;

break;

default default: /* ??? */

printf(“Illegal direction”);

break;

}

char direction = ‘e’;

/* somewhere set direction */

char opposite_direction;

if if(direction == ‘n’) {

opposite_direction = ‘s’;

} else {

if if(direction ( == ‘w’) ) {

opposite_direction = ‘e’;

} else {

if if(direction == ‘s’) {

opposite_direction = ‘n’;

} else {

}

}

}

if if(direction == ‘e’) {

opposite_direction = ‘w’;

} else {

printf(“Illegal direction”);

}

© PG/HC 2007 Computation 5JJ70 pg 15


What is the real difference between

switch() and if() ?

• Rule of thumb: Use switch() when:

– There are more than 2 similar choices AND

– Th The ddecision i i variable i bl i is an iinteger t or a character h t

• In all other cases, use if()

• By investigating the resulting machine code, we can reverse-engineer what

really happens!

•Open it up

• Ask yourself: why was it built like

this?

© PG/HC 2007 Computation 5JJ70 pg 16


A detailed look at the machine code

char direction = ‘e’;

/* somewhere set direction */

char opposite_direction;

if if(direction if if(direction == ‘n’) n ) {

opposite_direction = ‘s’;

} else {

if if(direction == ‘w’) {

opposite_direction = ‘e’;

} else {

if if(direction == ‘s’) {

opposite_direction = ‘n’;

} else {

}

}

}

if if(direction if if(direction == ‘e’) e ) {

opposite_direction = ‘w’;

} else {

printf(“Illegal direction”);

}

© PG/HC 2007 Computation 5JJ70 pg 17


A detailed look at the machine code

What's happening

h here? ?

char direction = ‘e’;

/* somewhere set direction */

char opposite_direction;

switch switch(direction) ( ) {

case ‘n’: /* north */

opposite_direction = ‘s’;

break;

case ‘w’: /* west */

opposite opposite_direction direction = ‘e’;

break;

case ‘s’: /* south */

opposite_direction = ‘n’;

break;

case ‘e’: /* east */

opposite_direction = ‘w’;

break;

default default: /* ??? */

printf(“Illegal printf( Illegal direction direction”); );

break;

}

© PG/HC 2007 Computation 5JJ70 pg 18


ASCII table: 1 byte encoding

AAmerican i St Standard d d CCode d ffor IInformation f ti IInterchange t h

9

5

4

© PG/HC 2007 Computation 5JJ70 pg 19


Recap: Program structure and blocks

void main(void) {


if(answer1 == ‘y’) {

printf(“…

}


} else {

if(a+b+c if(a+b+c == 0) {

printf(“Error…


} else {

if(a > b) {


} else {

if(b >= c) {


}

}

printf(“answer is …”);

}

}

printf(“good printf( good bye bye\n bye bye\n”); n n”); );

void main(void) {


if(answer1 == ‘y’) {printf(“…} else {

if(a+b+c == 0) { … } else {

if(a > b) {…} else { if(b >= c) {… }}

printf(“answer is …”);}}

printf(“good bye\n”);}

• Every { has a matching }

•Always l indent d a bl block. k

• Always put the accolade

in a consistent spot.

• N Never two t consecutive ti

open-accolades: {{

© PG/HC 2007 Computation 5JJ70 pg 20


Good coding practices (1)

•Use English

– The international language of Engineering is English. Therefore,

all variable names, names and all comment in the code should be in

English.

– Notice that even Dutch singers Rene Froger, Anita Meyer and

Lee Towers, Chipz, use English exclusively. Even Pim Fortuyn†

tid tried it. it

• Use as much as possible comment in the code:

– Professional code is maintained by different people over many

years, much longer than you think!

– Describe what you were thinking, and what it is supposed to do.

–Put your y name and student number on top p of f each file. f

• Give variables meaningful names names.

– There is no limit on the variable string length, so you can use as

many characters h t as you want: t conversion_rate

i

© PG/HC 2007 Computation 5JJ70 pg 21


Good coding practices (2)

•Always indent blocks properly.

• Empty lines are OK: they do not make a compiled program slower!

• Never more than one statement per p line!!

– This clarifies.

– This helps debugging. if(a > b) { biggest = a; }

• Always put braces around the body of if statements to avoid this

bug:

if(value > maximum)

maximum = value;

printf(“new maximum reached\n”);

average += value;

© PG/HC 2007 Computation 5JJ70 pg 22


Good coding practices (3)

• Check your input! Never over-estimate the intelligence

of the users!

• Illegal input should never, ever, cause the program to

crash.

• In the case of wrong input, print an error message:

if(input_value < 0) {

printf(“negative input value is illegal\n”);

exit(1);

}

© PG/HC 2007 Computation 5JJ70 pg 23


variable types

type number of bytes range

char 1 all ascii characters

unsigned char 1 [0, 255]

short int 2 [-32768 , 32767]

unsigned short int 2 [0 , 65536]

int 4 [-2^31 , 2^31>

unsigned int 4 [0 , 2^32>

float 4 [-3.2x10^38, 3.2x10^38]

double 8 [-1.7x10^308, 1.7x10^308]

•The function sizeof() returns the size (expressed in bytes):

double neuzel;

printf(“The size of an int is %d\n”, sizeof(int));

printf(“The size of variable neuzel is %d\n”, sizeof(neuzel));

The size of an int is 4

The size of variable neuzel is 8

© PG/HC 2007 Computation 5JJ70 pg 24


Declaring variables in C and C++

• The generic format is:

;

• SSuch h variable i bl is not nottt iinitialized! iti li d! ( (why?) h ?)

• To initialize a variable immediately:

= ;

int a;

double b;

unsigned short c;

int a = 12; /* integer 12 */

unsigned int b = 12u; /* 12 as unsigned int */

double c = 12.0; /* float or double 12 */

float d = 1e6; /* / d = 10^6 10 6 = 1000000 */ /

int e = 0xffffffff; /* 32-bit hexadecimal */

char f = ‘\n’; /* character */

© PG/HC 2007 Computation 5JJ70 pg 25


More on variables

• You can declare multiple variables at once. Separate by comma:

int month = 9;

int day = 11;

int year = 2001;

int month = 9, day = 11, year = 2001;

iint month h = 99,

day = 11, year = 2001;

• Rules for variable names:

– 1) They must be unique in the block (but not between blocks!)

– 2) Must not be any of the reserved keywords, such as char,

else, if, void, continue, etc etc

– 3) Should not start with a number; start with letter or _

• Good use:

– A) Local variables are all lower case.

– B) Use clear variable names, the size is unlimited!

© PG/HC 2007 Computation 5JJ70 pg 26


Constants in C++

• Constants are declared by putting ‘const’ in front to the declaration:

const char newline = ‘\n’;

const unsigned short int maxbyte = 255;

const double euro_conversion_rate = 2.20371;

• Main purposes:

– Avoids programming errors (e.g. accidentally changing the

conversion rate)

• A const cannot be changed, and therefore must be

initialized immediately at declaration

–Slightly g y faster and slightly g y more compact p code.

• Another qualifier is register, that tells the compiler to keep the

variable in the (fast) registers: g

register int a;

register unsigned long int b;

© PG/HC 2007 Computation 5JJ70 pg 27


enum data type

• This is a convenient way to implements sets.

• enum variables are actually integers.

enum Day {

Monday, Tuesday,

Wednesday, Thursday,

Friday, Saturday, Sunday };

enum Professor {

Pineda = 1,

Otten = 3, Groeneveld,

Corporaal};

void main (void)

{

Day today = Thursday;

Professor teacher = Groeneveld;

}


if(teacher == Otten && today == Monday)

……

© PG/HC 2007 Computation 5JJ70 pg 28


Arithmetic operators

• There are 5 arithmetic operators:

+ addition

- subtraction

* multiplication

p

/ division

% remainder (integer only)

• Operator precedence applies (‘Meneer Van Dale Wacht Op

Antwoord’)

result = a-b*d+e/f; // OK, but did we mean to do this ?

Wh When in i doubt, d bt always l use braces: b

result = (((a - b) * d) + e)/ f;

© PG/HC 2007 Computation 5JJ70 pg 29


Things to watch out for

• Take care of the types of the operands!

int

int int

float a = 5 / 3; // a = 1.00000000

float b = 5.0/3.0; // b = 1.66666667

double double

• In case the types are different, the ‘most accurate one’ wins:

double c = 4 / 3.0; // c = 1.33333333

int

double

• Never, ever divide by zero! The program will crash.

double c = a / b; // are we sure that b is not 0??

© PG/HC 2007 Computation 5JJ70 pg 30


More on ‘type conversion’

• As we noted, C and C++ use implicit type conversion. Example:

int a = 65; // ascii value of ‘A’

char b;

double c;

b = c = a; // c = 65.0 b = ‘A’

WWarning: i conversion i may lloose significant i ifi t bit bits

• We can make this type cast explicit. This will avoid the above

compiler p warning: g

int a = 65;

char b = (char) ( ) a; ;

Explicitly cast a to character

© PG/HC 2007 Computation 5JJ70 pg 31


• What’s wrong here??

Pop quiz!

unsigned char a = 32;

int b = 8;

a = a * b;

printf(“a = %d”, a);

• And what goes wrong here?

const unsigned short a;

long int b = -12;

a = b * b;

printf(“a i tf(“ = %d” %d”, a);

)

© PG/HC 2007 Computation 5JJ70 pg 32


Summary

• All variables need to be declared before use

• We must take care of the variable type

– Implicit conversion

–Overflow

– Use const to make sure it doesn’t doesn t change

•Expressions p can be made awfully y complex. p

• Good coding practice: proper indentation

© PG/HC 2007 Computation 5JJ70 pg 33

More magazines by this user
Similar magazines