structured programming anc/c++ declaration, deÞnition, objective, and executable Þles practical...

9
B16 Software Engineering Structured Programming Lecture 2: Control flow, variables, procedures, and modules Dr Andrea Vedaldi 4 lectures, Hillary Term For lecture notes, tutorial sheets, and updates see http://www.robots.ox.ac.uk/~vedaldi/teach.html Lecture 2 outline Control flow Imperative languages Goto (considered harmful) Blocks, conditionals, loops State Variable Data types Static vs dynamic typing Compiled vs interpreted language MATLAB functions, subfunctions, toolboxes C/C++ declaration, definition, objective, and executable files Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control flow Imperative languages Goto (considered harmful) Blocks, conditionals, loops State Variable Data types Static vs dynamic typing Compiled vs interpreted language MATLAB functions, subfunctions, toolboxes C/C++ declaration, definition, objective, and executable files Practical notes Clean vs obfuscated code Avoid cut & paste 3 Control flow An imperative program is a list of statements (instructions) Statements are executed sequentially incrementing the program counter 10 sleep eight hours 11 wake up 12 have breakfast Branching statements allow for non-sequential execution, conditionally on the state reset the program counter 13 if today is Saturday goto 10 14 leave home 4 10 PC 11 12

Upload: others

Post on 24-May-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

B16 Software EngineeringStructured ProgrammingLecture 2: Control flow, variables, procedures, and modulesDr Andrea Vedaldi 4 lectures, Hillary Term

For lecture notes, tutorial sheets, and updates see http://www.robots.ox.ac.uk/~vedaldi/teach.html

Lecture 2 outlineControl flow

Imperative languagesGoto (considered harmful)Blocks, conditionals, loops

StateVariableData typesStatic vs dynamic typing

Compiled vs interpreted languageMATLAB functions, subfunctions, toolboxesC/C++ declaration, definition, objective, and executable files

Practical notesClean vs obfuscated codeAvoid cut & paste

2

Lecture 2 outlineControl flow

Imperative languagesGoto (considered harmful)Blocks, conditionals, loops

StateVariableData typesStatic vs dynamic typing

Compiled vs interpreted languageMATLAB functions, subfunctions, toolboxesC/C++ declaration, definition, objective, and executable files

Practical notesClean vs obfuscated codeAvoid cut & paste

3 Control flowAn imperative program is a list of statements (instructions)

Statements are executed sequentially incrementing the program counter10sleepeighthours11wakeup12havebreakfast

Branching statements allow for non-sequential execution, conditionally on the statereset the program counter13iftodayisSaturdaygoto1014leavehome

4

10PC 1112

Page 2: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

Control flow wit gotoBASIC example 10i←020i←i+130printi,“squaredis“,i*i40ifi>=10thengoto6050goto2060print“that’sallfolks!”

To add a line of code use an intermediate line number (!)

10i←020i←i+130printi,“squaredis“,i*i35printi,“cubedis“,i*i*i40ifi>=10thengoto6050goto2060print“that’sallfolks!”

“Goto”s 5

Use labels to abstract line numbers and simplify the use of gotoA label is just a name given to a statement in the sequence i←0more:i←i+1 printi,“squaredis“,i*i ifi>=10thengotoend gotomoreend: print“that’sallfolks!”

Labels 6

spaghetti code

[Dijkstra, E. W. (1968). Letters to the editor: go to statement considered harmful. Communications of the ACM, 11(3), 147-148.]

Structured Control Flow

Give up goto altogether. Any program can be expressed in term of three simple control structures [Böhm-Jacopini 66]:

Blocks (sequences of executable statements){do_this;do_that;do_something_else;}

Conditionals (execute a block if condition is true)if(condition){}

Loops (keep executing a block until condition is true)while(condition){}

7

i←0more: i←i+1 printi,“squaredis“,i*i ifi>=10thengotoend gotomoreend: print“that’sallfolks!”

i←0while(i<10){i←i+1printi,“squaredis“,i*i;}print“that’sallfolks!”

Spaghetti monster Structured program

Obvious flow

Structured Control Flow

The code is much easier to understand because each block hasonly one entry point at the beginningonly one exit point at the end

Example

8

i←0more: i←i+1 printi,“squaredis“,i*i ifi>=10thengotoend gotomoreend: print“that’sallfolks!”

{ i←0 while(i<10) { i←i+1 printi,“squaredis“,i*i; } print“that’sallfolks!”}

Structured programSpaghetti monster

Page 3: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

Structured Control Flow: ProceduresA way to create a software module or component is to wrap a sequence of statements into a procedure.

A procedure implements a reusable functionality (behavior)hiding the internal implementation details.

Examples- y=tan(x)//computethetangentofanumber

- printf(“astring”)//displayastringonthescreen

- window=createWindow()//createanewwindowonthedisplay

- destroyWindow(window)//destroyit

9

procedureprint_n_squared_numbers(n){ i←0 while(i<n) { i←i+1 printi,“squaredis“,i*i; } print“that’sallfolks!”}

proceduredo_something(){ print“firstfoursquares” print_n_squared_numbers(4);}proceduredo_something_more(){ print“firsttensquares” print_n_squared_numbers(10);}

MATLAB vs C 10

C version #include<stdio.h>voidprint_n_squared_numbers(intn){ inti=0; while(i<n){ i=i+1; printf("%dsquaredis%d\n",i,i*i); } printf("thatsallfolks!\n");}/*theprogramentrypointiscalledmain*/intmain(intargc,char**argv){ print_n_squared_numbers(10); return0;}

MATLAB version

functionprint_n_squared_numbers(n) i=0; whilei<n i=i+1; fprintf('%dsquaredis%d\n',i,i*i); end fprintf('that’sallfolks!\n');end%Exampleusageprint_n_squared_numbers(10);

Both MATLAB and C are imperative and procedural.MATLAB is interpreted, C/C++ is compiled

MATLAB is dynamically typed, C/C++ is statically typed.

Lecture 2 outlineControl flow

Imperative languagesGoto (considered harmful)Blocks, conditionals, loops

StateVariableData typesStatic vs dynamic typing

Compiled vs interpreted languageMATLAB functions, subfunctions, toolboxesC/C++ declaration, definition, objective, and executable files

Practical notesClean vs obfuscated codeAvoid cut & paste

11 Statements and the state

State = program counter + content of memory

Executing a statement changes the stateupdates the program counteralmost always modifies the content of the memory too

Example 50*x*x+y;//resultisnotremembered,noeffectz=50*x*x+y;//writetheresulttothevariablez

If a statement does not alter the content of the memory, it has essentially no effect

Exceptions:wasting timein MATLAB, displaying a value on the screen...

12

Page 4: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

Memory and variablesA computer’s memory is just a large array of words (strings of bit)

13

0000000000000001

...

FFFFFFFF

MEMORY(4GB)

Addresses

001F034C

66726564001F034C:

The meaning depends on how it is interpreted:32 bit integer 17187730924characters “fred”floating point 1.68302e+022

Write a 32-bit integer to memory in C*((int*)0x001F034C)=1718773092;

Structured version: using a variablemilesToGo=1718773092;

milesToGo:

A variable is just a label to a memory address

TypesA (data) type specifies

a set of possible values e.g. integers in the range −2,147,483,648 to 2,147,483,647what one can do with theme.g. create, assign, sum, multiply, divide, print, convert to float, ...

A data type representation specifies how values are actually stored in memorye.g. integer is usually represented as a string of 32 bits, or four consecutive bytes, in binary notation

This is a another example of abstractionYou never have to think how MATLAB represents numbers to use them!

Every language support an array of primitive data types:MATLAB: numeric arrays (characters, integer, single and double precision), logical arrays, cell arrays, ....C: various integer types, character types, floating point types, arrays, strings, ...

14

Dynamic typingConsider the following MATLAB fragment%x,y,andzarestoredas64-bitfloatx=5;y=10;z=x*y;

Each variable stores both:the address of the data in memory andthe type of the data.

Use MATLAB command who to get a list of variables and their types:NameSizeBytesClassx1x18doubley1x18doublez1x18double

15

MEMORY

5x:

10y:

50z:

Dynamic typingConsider the following MATLAB fragment%x,y,andzarestoredas64-bitfloatx=5;y=10;z=x*y;

16

MEMORY

5x:

10y:

50z:

Page 5: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

Consider the following MATLAB fragment%x,y,andzarestoredas64-bitfloatx=5;y=10;z=x*y;%nowreassignxandzx='OxfordU';z=x*y;

Now x refers toa new memory block anda different data type.

In MATLAB, the data type associated to a variable can be determined only at run-time, i.e. when the program is executed

This is called dynamic typing

Dynamic typing 17

5

10

50z:

“Oxford U”x:

[1 x 8 array]z:

MEMORY

Consider the following MATLAB fragment%x,y,andzarestoredas64-bitfloatx=5;y=10;z=x*y;%nowreassignxandzx='OxfordU';z=x*y;

What is z? NameSizeBytesClassx1x816chary1x18doublez1x864double

Two operations are involved in calculating z:

promotion: the string x is reinterpreted as an array of 1⨉8 numbersvector-matrix mult.: the scalar y is multiplied by this array

Dynamic typing 18

5

10

50z:

“Oxford U”x:

[1 x 8 array]z:

MEMORY

In dynamic typing each a variable is associated to both the actual data record as well as metadata describing its type.

While usually this is not a problem, in some cases the overhead may be significant.

Example: MATLAB uses about 80 bytes to store the data type descriptor.

Storing one array of 1 million numbers uses80 + 8 * 1e6 bytes (~ 7.6 MB, efficiency ~ 100%)Storing 1 million arrays of 1 number each uses(80 + 8) * 1e6 bytes (~ 83 MB, efficiency ~ 9%)

Overhead in dynamic typing 19

“Oxford U”

x: Type = string

3.14

Type = arrayy:

MEMORY

Static typing and variable declarationIn C variables must be declared before they can be used

A declaration assigns statically a data type to a variable

ExamplesintanInteger;/*usually32bitslength,butimplementationdependent*/ unsignedintanUnsignedInteger;charaCharacter;doubleaFloat;int32_ta32BitInteger;/*C99andC++*/int16_ta16BitInteger;

Statically-typed variableshave a well defined type before the program is runincorporate constraints on how a variable can be used

Static typing allows forsmaller run-time overhead in handling variablesbetter error checking before the program is run

20

Page 6: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

Lecture 2 outlineControl flow

Imperative languagesGoto (considered harmful)Blocks, conditionals, loops

StateVariableData typesStatic vs dynamic typing

Compiled vs interpreted languageMATLAB functions, subfunctions, toolboxesC/C++ declaration, definition, objective, and executable files

Practical notesClean vs obfuscated codeAvoid cut & paste

21 Compiled vs interpreted languageMATLAB is an interpreted language

a MATLAB program is executed by an interpreterthe interpreted emulates a CPU capable of understanding MATLAB instructionssignificant overhead at run-time

C and C++ are compiled languagesa C/C++ program must be translated by a compiler into an executable format before it can be executedno overhead at run-timethe compiler can spot programming error violating assumptions expressed in the code

for example, in a statically typed language the compiler can check that operations on variables involve data of the correct types

Example Compiling the following fragment generates an error because the multiplication of an integer and a pointer (see later) is not defined:int*aPointerToInt=0;intanInt=10;intanotherInt=anInt*aPointerToInt;error-pointer-by-integer.c:7:error:invalidoperandstobinary*(have‘int*’and‘int’)

22

MATLAB: program organisationMATLAB procedures are called functions

A MATLAB function is stored in a homonymous file with a .m extension

23

functionprint_ten_squared_numbers(n) i=0; whilei<n i=i+1; fprintf('%dsquaredis%d\n',i,i*i); end fprintf('that’sallfolks!\n');end

file: print_ten_squared_numbers.m%demonstratestheuseofafunctionprint_ten_squared_numbers()

file: my_script.m

A .m file can also contain a script.

A script does not define a function. It is more similar to cutting & pasting code in to the MATLAB prompt.

MATLAB: program organisationMATLAB procedures are called functions

A MATLAB function is stored in a homonymous file with a .m extension

24

functionprint_ten_squared_numbers(n) i=0; whilei<n i=i+1; fprintf('%dsquaredis%d\n',i,i*i); end thats_all();endfunctionthats_all() fprintf('that’sallfolks!\n');end

file: print_ten_squared_numbers.m%demonstratestheuseofafunctionprint_ten_squared_numbers()

file: my_script.m

An .m file defines a function that can be accessed by functions and scripts in other files.

A .m file can contain also any number of local functions.

Local functions are only visible from the file where they are defined.1

1Advanced techniques allow to pass references to local functions, so that they can be called from other files.

Page 7: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

MATLAB: grouping related functionsPut related functions into a given directoryDirectory: drawing/drawAnArc.m drawAnArrow.m drawACircle.m Directory: math/tan.matan.m sqrt.m Directory: pde/euler.m

Use MATLAB addpath() function to include directories in MATLAB search path and make these functions visible.

MATLAB Toolboxes are just collections of functions organised in directories.

25 C/C++: program organisationC/C++ explicitly support the notion of modules.

A module has two parts:the declaration (.h), defining the interface of the functionsi.e. the function names and the types of the input and output arguments

the definition (.c), containing the actual implementation of the functions

26

#include"usefulstuff.h"#include<stdio.h>voidprint_n_squared_numbers(intn){inti=0;while(i<n){i=i+1;printf("%dsquaredis%d\n",i,i*i);}printf("thatsallfolks!\n");}intget_an_awesome_number(){ return42;}

file: usefulstuff.cvoidprint_n_squared_numbers(intn);intget_an_awesome_number();

file: usefulstuff.h

#include"usefulstuff.h"intmain(intargc,char**argv){print_n_squared_numbers(10);}

file: myprogram.c

C/C++: compiling a programRun the compiler ccEach .cfile is compiled into an object file .oThis is the binary translation of a module

Run the linker, usually also implemented in ccThe .ofiles are merged to produce an executable file

27

declaration file: usefulstuff.h

usefulstuff module

definition file: usefulstuff.c

declaration file:N/A

myprogram module

definition file: myprogram.c

object file: usefulstuff.o

object file: myprogram.o

compile compile

executable file: myprogram

link

C/C++: compiling a programRun the compiler ccEach .cfile is compiled into an object file .oThis is the binary translation of a module

Run the linker, usually also implemented in ccThe .ofiles are merged to produce an executable file

28

declaration file: usefulstuff.h

usefulstuff module

definition file: usefulstuff.c

object file: usefulstuff.o

declaration file:N/A

myprogram module

definition file: myprogram.c

object file: myprogram.o

executable file: myprogram

compile compile

link

declaration file: morestuff.h

morestuff module

definition file: morestuff.c

object file: morestuff.o

compile

Page 8: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

More on declaring, defining, and calling functions

Declaring a functiondefines its prototype = {name of the functions, type of input/output parameters}specifies the interface given the prototype, the compiler knows how to call the function

Defining a function specifies its implementation. The parameters are said to be formal as their value is not determined until the function is called.

Calling a function starts executing the function body. The parameters are said to be actual because they are assigned a value.

29

Declaration of the function prototypevoidprint_n_squared_numbers(intn);

Definition of the function implementationvoidprint_n_squared_numbers(intn){ /*dosomething*/}

Invocation of the functionprint_n_squared_numbers(10);

formal parameter actual parameter

Return value(s)

In C functions have a single output value, assigned by the return statement.

In MATLAB functions have an arbitrary number of output values.They get their value from homonymous variables.

30

Definition of the functionintget_awesome_number(){ return42;}

Invocation of the functionintx;x=get_awesome_number();/*xvalueisnow42*/

Definition of the functionfunction[a,b,c]=get_many_numbers() a=42; b=3.14; c=+inf; return;end

Invocation of the function%xgets42,y3.14,andz+inf[x,y,z]=get_many_numbers();%geteigenvectorsandeigenvalues[V,D]=eig(A);

Control flowImperative languagesGoto (considered harmful)Blocks, conditionals, loops

StateVariableData typesStatic vs dynamic typing

Compiled vs interpreted languageMATLAB functions, subfunctions, toolboxesC/C++ declaration, definition, objective, and executable files

Practical notesClean vs obfuscated codeAvoid cut & paste

31 Some practical notesThe look is important

Use meaningful variable namesUse comments to supplement the meaningIndent code for each block/loop

Avoid to cut and paste codeUse functions to encapsulate logic that can be reusedCutting and pasting code leads to guaranteed disasters

because when you need to change the code,you need to change all the copies!

Top-down vs bottom-upDesign top-downCode bottom-up or top-down, or a combination

32

Page 9: Structured Programming AnC/C++ declaration, deÞnition, objective, and executable Þles Practical notes Clean vs obfuscated code Avoid cut & paste 2 Lecture 2 outline Control ßow

Obfuscated code (don’t)Here is a valid C program (http://en.wikipedia.org/wiki/Obfuscation_(software))charM[3],A,Z,E=40,J[40],T[40];main(C){for(*J=A=scanf("%d",&C); --E;J[E]=T [E]=E)printf("._");for(;(A-=Z=!Z)||(printf("\n|" ),A=39,C-- );Z||printf(M))M[Z]=Z[A-(E=A[J-Z])&&!C &A==T[A] |6<<27<rand()||!C&!Z?J[T[E]=T[A]]=E,J[T[A]=A-Z]=A,"_.":"|"];}

Can you figure out what this does?

33