AM38: Intermediate Level Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 57

AM38: Intermediate Level

Programming
Kasper Støy (
[email protected])

(Based on presentation by Ivar Balslev)


Who am I?
 Brief CV
– MSc computer science (Århus University, 1999)
– Research Assistant (USC Robotics Labs, Los
Angeles, 2000)
– Visiting Ph.D. Student (USC Information
Sciences Institute, Los Angeles, 2002)
– Ph.D. computer system engineering (University
of Southern Denmark, 2003)
– Assistant Professor (University of Southern
Denmark, 2003-?)
What do I do?
Contact
Aims
 Theoretical understanding of C and C++
– Overview
– Code organization
– Speed optimization
– Memory management
– Compiling libraries
 Practical experience in programming C and
C++
Why C/C++?
 Java is becoming the programming
language of choice, but
– On small microcontrollers it is not possible to
implement a java virtual machine
– The automatic memory management of JAVA
cannot be controlled and this is a problem in
some time-critical applications
– C/C++ will still be the main programming
languages in industry for the next 5-10 years.
Java vs C++
 Java
– Simple dynamical memory allocation
– Automatic memory deallocation
– Variable transfer ’by reference’ as default
 C++
– Dynamical memory allocation less simple
– Deallocation must be coded
– Variable transfer in methods must be specified
Schedule
 Sep. 1:
– Concepts and rules assumed known
– Memory administration of single instances
– Classes in C++, part 1
 Sep. 8:
– Classes in C++, part 2 (operators and templates)
– Speed considerations
– Memory administration of arrays
 Sep. 15:
– Standard template library
– Using and making compiled libraries
– Code organization
– The exercises and the final mini project
Types of Programming Languages
 Machine
 Assembly
– Translated to machine language
 Compiled (C++, PASCAL, JAVA*)
– Compiled into machine language (*java into a
machine language of a virtual computer)
 Intepreted (Basic)
Concepts and rules assumed known
(1)
 RAM (random access memory)
 Simple types bool, int, float ..
 Variables float x,y;
 Functions in standard C++ exp, ln,..
 Assignments int x = z*sin(y);
 Comparisons bool q = (x>3);
 Comparison operators ==, !=, >,..
 if-else statements if (q){..} else {..}
 Loops (for, while, do-while)
 Statements and declarations
 Semicolon after statements and declarations
Concepts and rules assumed known
(2)
 Casting between simple types x=(float)i/j;
 Using braces {}
 Using parentheses ()
 The scope of a declaration
– code between the declaration and
– the right brace ( } ) which corresponds
– to the nearest preceding left brace ( { )
 Non-simple types (structs: typedef struct{float x,y} TPos;)
 Occupied memory of types (Bytes)
 Procedures/functions/methods
You should understand this
#include "stdio.h” //except this

int plus( int a, int b ) {


return(a+b);
}

int main(int argc, char* argv[]) //and this


{
int x=2, y=4;
printf(”%d+%d=%d", x, y, plus(x,y));
return 0;
}
Single instances of simple types and
’structs’
 Simple types: bool, int, float, long int, double..
– int p; *)
– float x,y; *)
 ‘structs’: Bundles of variables
– typedef struct {int i,j; float x;} TStruct1;
– Static allocation and use of ‘structs’
– TStruct1 Struct; *)
– Struct.x = 3.0;
– p = Struct.j;

*)Here is memory statically allocated


Procedures/function/methods

 Pieces of code to be used in different contexts.


 Prototype:
– int Proc1(float x,float y, int i);
 Specification:
– int Proc1(float x,float y, int i) {return i*(x+y)};
 Call:
– j = Proc1(1.2,z,3);
 Parameters can be passed by value, pointer, or reference.
 Procedures do not return anything. Functions do. In object
oriented languages functions and procedures are called
‘methods’
Pointers
 Pointers are used in two situations:
– When handling arrays of simple types and ‘structs’ (to
be treated later)
– When passing information to and from methods.
 float* p;
– implies that p points at a variable of type float.
– p is the memory address of the variable.
 p is statically allocated as a pointer type, but no
memory for the variable pointed at is allocated.
 After proper allocation, *p means the variable
pointed at by p
References
 Are used to pass information to and from a
method. One uses the & operator so that &A
means a pointer to the variable A
Outputs from methods
 Three ways of transferring output variables
of methods
– Using functions returning the output
– Using pointers in the variable list
– Using references in the variable list
Using functions returning the output

float Method1(float x,float y) {


float result;
result = <some calculation>;
return result;
}
Using pointers in the variable list
void Method2(float x,float y, float *result) {
*result = ..;
}
Using references in the variable list

void Method3(float x,float y, float &result) {


result = ..;
}
Inputs to Methods

 Three ways of passing input variables to


methods:
– By value
– By pointer
– By reference
Input By Value
float Method1(float x) {
..= x + x*x;
..;
}

 Copies x to the stack during transfer


Input By Pointer
float Method2(float *px) {
..= *(px)+(*px)*(*px);
..
}

 Inside the method, the pointer px to the


relevant variable is used.
Input By Reference
float Method3(const float &x) {
.. = x+x*x;
..
}

 Inside the method, the pointer to x is used.


 const indicates a pure input variable (no
assignments inside the method)
Memory Management
Memory Management
 The programmer must explicitly allocate
dynamic memory and deallocate it after use.
 C:
– Allocate: Int *i = (int) malloc( sizeof(int) );
– Deallocate: free(i);
 C++:
– Allocate: int *i = new int
– Deallocate: delete(i)
Example
int *c = malloc( sizeof( int ) );
*c=5;
….
free( c );
Memory Leak
int i;
int *p;
p = (int) malloc( sizeof( int ) );
p = &i;

 The chunk of memory p pointed to initially is


lost forever (until program termination).
Classes in C++
Classes in C++
 C++ is an object oriented extention of C
Syntax: class CMyClass {...};
 The content of {...} are the following:
– Declaration/instantiation of data members
(simple types, structs, or classes)
– Prototypes of member methods
– One or more constructors
– A destructor
Class example
In file ”MyClass.h”:

Class MyClass {
int *i; // member variable
int plus( int a, int b ); // method
MyClass(); // constructor
~MyClass(); // destructor
}
Class Example
In file ”MyClass.cpp”:

#include ”MyClass.h”
Int MyClass:: plus( int a, int b ) {
return( a + b );
}
MyClass::MyClass() {
i = new int;
}
MyClass::~MyClass() {
delete i;
}
Class Example
#include "MyClass.h"

int main(int argc, char* argv[]) {


MyClass m;
printf("%d", m.plus(3,4));
return 0;
}
Lecture II
Schedule
 Wednesdays September 1st and 15th 10.15-
12.00: Lectures in room u49b
 NOTE, NEW TIME: unknown?
 Nothing on Thursdays
Operator overloading
 With integers it is obvious what the following
statements do.
a=2+7
a == 5
 These operators (+,-,=,…) can be
overloaded to mean something different for
other classes
class CPoint2D {
public:
int m_x, m_y;

inline void operator = (const CPoint2D& P2D) {


m_x=P2D.m_x;
m_y=P2D.m_y;
};

inline CPoint2D operator + (const CPoint2D& P2D) {


CPoint2D Buf = *(this);
Buf.m_x+= P2D.m_x;
Buf.m_y+= P2D.m_y;
return(Buf);
}
};
Overloading
 We can now write:
CPoint2D a,b,c;
a.x=2; a.y=4; b.x = 1; b.y = 2;
c = a + b; //result c.x = 3 and c.y=6
Templates
 We have now written CPoint2D that works
with integers, but what if we wanted to use
floats instead?
template<class T> class CPoint2D {
private:
T m_x, m_y;

public:
CPoint2D(); //constructor defined in cpp file
~CPoint2D(); //destructor defined in the cpp file

inline void operator = ( const CPoint2D<T>& P2D)


{ m_x=P2D.m_x;m_y=P2D.m_y;
}

inline bool operator == ( const CPoint2D<T>& P2D ) const {


return( P2D.m_x==m_x && P2D.m_y == m_y );
}
}
Using a Template
 CPoint2D<float> a, b, c;
Speed considerations
 Increment operators
 Move code out of loops
 Shifting vs. division/multiplication
 Integer vs. float
 Reindexing vs. swapping
Memory Management
 Static memory allocation:
Int M[100];
For(int i=0;i<100;i++) M[i]=0; //remember to init

 Dynamic memory allocation:


T *M =(T*)calloc(n,sizeof(T));
….
M=(T*)realloc(M,new_size*sizeof(T));
….
free(M)
Lecture III
Standard Template Library (STL)
 Many of the standard data structures are
implemented for you to use in STL
Vector
 vector<T> M;
 M.push_back(t);
 M.insert(itr,t);
 M[i]=t;
 M.resize(p);
 M.empty();
 M.pop_back();
 M.erase(itr);
 M.sort();
Iterators
 vector <T>::iterator itr;
– E.g. vector<int>::iterator itr;
 Itr = M.begin();
 Itr = M.end();
 If *itr = M[0] => *(++itr) == M[1]
Multi-Dimensional Arrays
T M[100][100] //static

T **M; //dynamic
M = (T**)calloc(m,sizeof(T*));
for(int i=0;i<m;i++) M[i]=(T*)calloc(n,sizeof(T));

for (int i=0;i<m;i++) free(M[i]);


free(M).

vector<vector<T> > M
(note!!!!! the space between > and >)
Robot Mini Project
Robot Mini Project
 Aims
– Introduction to programming in Unix
– Introduction to the Player/Stage multi-robot
simulation tool
– Show off your powerful c++ skills
Robot Mini Project
 Your task
– Program a mobile robot controller using c++
 Your c++ program linked with a library
connects across the network and controls a
robot
The Pioneer Robot
 Two wheels (can rotate
on the spot)
 A sonar array with 16
sonars
 (A laser ranger finder
sweeping -90 to 90
degrees)
 We will use a simulation
of this robot
Simulation Overview
C++
Client
YOUR
Library PRG.!
int main(int argc, char *argv[]) {
PlayerClient robot("localhost", atoi(argv[1]));
Example SonarProxy sp(&robot,0,'r');
PositionProxy pp(&robot,0,'w');
int newturnrate,newspeed, i=0;
while(true) {
if(robot.Read()) exit(1);

// make turnrate dependent on sonar readings


if((sp.ranges[0]+sp.ranges[1])<(sp.ranges[6]+sp.ranges[7]))
newturnrate = -20;
else
YOUR newturnrate = 20;

PRG.! if(sp.ranges[3] < 500)


newspeed = 0;
else
newspeed = 100;

pp.SetSpeed(newspeed,newturnrate);
}
}

You might also like