Lecture 2 Struct and Functions Variable (1 of 2) Consists of: - - PowerPoint PPT Presentation

lecture 2
SMART_READER_LITE
LIVE PREVIEW

Lecture 2 Struct and Functions Variable (1 of 2) Consists of: - - PowerPoint PPT Presentation

Lecture 2 Struct and Functions Variable (1 of 2) Consists of: Name so we can refer to its storage location at lower level converted to an adress in memory can be aliased by way of reference Value what we store in the


slide-1
SLIDE 1

Lecture 2

Struct and Functions

slide-2
SLIDE 2

Variable (1 of 2)

Consists of:

  • Name

– so we can refer to it’s storage location – at lower level converted to an adress in memory – can be aliased by way of reference

  • Value

– what we store in the location – will never be empty, not even before we fill it

  • Type

– size of storage location – interpretation of stored value

slide-3
SLIDE 3

Variable (2 of 2)

Three kinds of variables:

  • Fundamental (basic)

– stores a value of fundamental type, nothing more

  • Object

– stores values tied to an derived type (struct, class, union, enum) – operations associated to the type are provided – more later in the course

  • Pointer

– stores just the adress of some other variable – requires caution: what if the adress does not contain said variable? – more later in the course

slide-4
SLIDE 4

Struct

With struct it is possible to combine variables into one derived type struct Person { string first_name; string last_name; int age; };

slide-5
SLIDE 5

Constants

  • A variable can be declared const
  • Modification of a const variable will give compilation

error.

  • The compiler can treat constant variables more

efficiently.

  • The programmer have less worries with constant

variables than other. Big benefit!

  • A const variable is much better than a literal because

you refer to it by name, and change it at one place.

  • Constants use upper case letters by convention.

const int SIZE{1000};

slide-6
SLIDE 6

References

  • A varaible can be declared to be an alias for an

already existing variable

  • The existing variable gets a second name, but

is in all other aspects identical to the new

  • The binding occur only once, at initialization

string professor{”C. Kessler”}; string & clever_fellow{professor};

slide-7
SLIDE 7

Sequence and block

  • A sequential list of statements
  • Each statement is terminated with a semicolon
  • All statements are inside some block
  • Entire block form a compound statement
  • Statements are executed one by one in order:

{ // beginning of block

statement1; statement2; statement3;

} // end of block

slide-8
SLIDE 8

Function (1 of 3)

  • A block that has been given a name
  • Can be executed (called) by writing it’s name in other parts
  • f the program, provide reusable code
  • Can accept input (parameters) from calling code
  • Can give (return) a result back to calling code

return-type function-name(parameter-list) {

statement1; statement2; return expression;

}

slide-9
SLIDE 9

Function (2 of 3)

  • A function must have a single well defined task. No side effects!
  • Function name should be well choosen.
  • The purpose, inputs, and result must be documented in a comment before

the function. Also document any assumptions, presumptions or special considerations.

// purpose: calculate sum of love // inputs: integers a, b // output: the sum of love (integer) int love(int a, int b) { return a + b; } // purpose: print v on stdout void marriage(int v) { cout << v << endl; } marriage(love(a,b)); // GOOD, individually reusable functions // what’s wrong above?

slide-10
SLIDE 10

Function (3 of 3)

  • Multipurposed functions are hard to reuse.
  • Functions with sid effects are hard to reuse.
  • Often seen in student code. BAD, BAD, Threefold BAD.

// BAD BAD BAD (oh well.. ;-) // You can’t have one without the other!!!

void love_and_marriage(int a, int b) { cout << a + b << endl; } love_and_marriage(a, b); // can’t do just love!!!!

slide-11
SLIDE 11

Function types

  • A function with no return value is often called

a subroutine or a procedure

  • A function part of an object variable is often

called a member function or a method

  • A function created inline, or ”on the fly” is

called a lambda function

  • An object possible to call as a function is

called a function object, and have operator() defined

slide-12
SLIDE 12

Function declaration and definition

  • The return-type, function-name and

parameter-list followed by a semicolon is a declaration.

  • If you specify the entire function body (block)

instead of semicolon it is a definition.

  • Declaration

– Tells the compiler the function exists somewhere.

  • Definition

– Places function code in program memory.

slide-13
SLIDE 13

Function input

  • Zero or more specified in parameter list
  • Parameters are variables that require a value in order

to call the function

  • Also called formal parameters
  • The value we assign to a parameter when calling a

function is called argument, or actual parameter

  • Datatype and order of arguments must match the

specified formal parameters

  • Automatic conversion can occur if compiler know a

way to convert from argument to formal parameter

slide-14
SLIDE 14

Input only parameters

  • Declared as normal variable when of fundamental

type.

– Arguments are copied to parameters – Efficient for fundamental (small) types void example(int normal_input);

  • Declared as const reference when of object type.

– Clear to programmers that object is not modified in the function, despite reference – Arguments are referred to from the function – Efficient for object (large) types void example(string const& object_input);

slide-15
SLIDE 15

Input/Output parameter

  • Declared as reference variable.

– Clutter-free and safe, compiler create binding (alias) between argument and parameter – Clear to programmers that values passed in may be modified by the function. – Arguments are referred to from the function void example(string& input_output);

  • Declared as pointer variable.

– Programmer must make correct binding – Code cluttered by adress-of (&) and content-of (*) operators – Allow three modes: input/output/unused – Set pointer to nullptr to indicate invalid or unused parameter, the function must explicitly include code to check for nullptr void example(string* p_out){ *p_out = ”goes out”; } example(&some_str); // take address of some_str at call

slide-16
SLIDE 16

Why not just return?

  • In some cases you need to ”return” several

values.

– Solve a 2:nd degree polynom (ax2+bx+c=0).

  • In some cases it does not make much sense

for a function to return something.

– Does not compute something from input.

  • In some cases it’s not very efficient

– Returning a value cause an extra copy operation.

slide-17
SLIDE 17

Default parameters

  • Parameters can be given default values
  • Specified in declaration only, since definition may be

unknown to compiler if program is in several files.

  • Default values can only be specified for last non-default

parameter

  • Can be omitted when calling the function

void ignore(int n = 1, char stop = EOF); ignore(); // call ignore(1, EOF) ignore(1024) // call ignore(1024, EOF); ignore(numeric_limits<int>::max(), ’\n’);

slide-18
SLIDE 18

Function result

  • Functions evaluate to exactly one result, specified by a

return statement

  • The result can be specified as nothing, void
  • The result can be specified as auto in C++11, meaning

it is specified later, NOT automatic

  • A function can terminate it’s block early by executing a

return statement early

  • The call to the function immediately evaluates to the

returned expression and continue execution at the point of call

  • A function automatically return void at end of it’s block
slide-19
SLIDE 19

Function scope

  • Formal parameters are variables local to it’s

function

  • Variables declared inside the function are local

variables to the function

  • Local variables can only be accessd inside it’s

function

  • All local variables cease to exist at point of

return

slide-20
SLIDE 20

Naming of parameters

  • The name should inform humans of the

purpose of the parameter, so we can specify it at point of call.

  • Good names are typically 5-20 characters.
  • Name must begin with a letter (or underscore)

and contain only letters and underscore

  • Names are case sensitive
slide-21
SLIDE 21

Overloading

  • Different functions can have same name
  • Functions with same name should be identical in

their purpose to avoid confusion

  • Functions with same name must have different

parameters

  • Arguments given determine which function is

actually called (closest match)

  • Compiler will select the ”best match” among

functions with same name

  • Return value is not considered even if different
slide-22
SLIDE 22

Overloading example

int triangle_area(int base, int height); int triangle_area(int side1, int side2, int side3); int triangle_area(int side1, int side2, float angle); int triangle_area(int side, float angle1, float angle2); triangle_area(1, 1); triangle_area(1, 1, 1); triangle_area(1, 1, 1.0); // which is called? triangle_area(1, 1.0, 1.0); triangle_area(1, 1, 1.0f); triangle_area(1, 1.0f, 1.0f); // can you add a default parameter to second version?

slide-23
SLIDE 23

Alternate function syntax

  • Sometimes you want to deduce the return

type from input parameters.

  • Parameters must then occur to the compiler

before the return type

  • Solved with auto and decltype in C++11

(both is also useful in other contexts)

auto sum(float a, int b)

slide-24
SLIDE 24

Lambda function

  • C++11 allows lambda functions, or ”inline” function

definition

  • Covered in detail later in course (when useful)

Pos origin{3,4}; vector<Pos> data; sort(data.begin(), data.end(), [&origin](Pos a, Pos b)->bool {

return dist(a,origin) < dist(b,origin);

});

slide-25
SLIDE 25

Facilitates divide-and-conquer (1)

  • It is easy to check if a chess queen may move if we know how

a rook and bishop may move.

  • Then just continue and implement the missing functions.
  • Note that functions make your code more readable!

bool is_legal_queen_move(Pos from, Pos to) { return is_legal_rook_move(from, to) || is_legal_bishop_move(from, to); }

slide-26
SLIDE 26

Facilitates divide-and-conquer (2)

bool is_legal_rook_move(Pos from, Pos to) { return is_horizontal_move(from, to) || is_vertical_move(from, to); } bool is_legal_bishop_move(Pos from, Pos to) { return is_diagonal_move(from, to); }

slide-27
SLIDE 27

Facilitates divide-and-conquer (3)

bool is_horizontal_move(Pos from, Pos to) { return from.y == to.y; } bool is_vertical_move(Pos from, Pos to) { return from.x == to.x; } bool is_diagonal_move(Pos from, Pos to) { return abs(from.x-to.x) == abs(from.y-to.y); }

slide-28
SLIDE 28

Recursion

  • In math you use induction as a way of thinking in order

to prove a theorem.

– prove the theorem for one case – prove that if true for some case, it’s also true for the next – by way of induction it’s true for all cases

  • In programming we can use a similar way of thinking to

get a result

– calculate the result in one specific input – write a function that calculates the result ov any input given the previous input – by way of calling itself, the calculation get to the specific input and calculate the result from there on

slide-29
SLIDE 29

Recursive definition

  • A recursive definition have two parts

– A starting (or ending) point – How you get from one to the next (or previous)

  • Consider N-factorial

– It’s possible to express by way of itself! – 0! = 1 – N! = N*(N-1)!

  • All computations can be written recursive!

– Sometimes it’s much shorter, simpler and clearer.

slide-30
SLIDE 30

N-factorial two ways

int factorial(int N) { if ( N == 0 ) return 1; return factorial(N-1); } int factorial(int N) { return prod_from_one(1, N); } int prod_from_one(int X, int N) { if ( X == N ) return N; return X*prod_from_one(X+1, N); }

slide-31
SLIDE 31

Exponentiation

// xy=Pow(x, y): // x * Pow(x, y-1) if y>0 // 1.0/Pow(x, -y) if y<0 // 1.0 if y=0 double pow(double x, int y) { if (y > 0) return x*pow(x,y-1) else if (y < 0) return 1.0/pow(x,-y) else // y == 0 return 1.0; // Gets here eventually! }

slide-32
SLIDE 32

File separation

  • Related (cohesive) functions can be gathered in one file to form a

package.

  • A package can be compiled separately, and do not need

recompilation unless you change a package source file.

  • Public declarations are place in a header file *.h
  • Definitions are placed in a implementaton file *.cc
  • Header and implementation files should have the same name,

except for the extension

  • Header file must have a preprocessor guard to protect from

multiple inclusion #ifndef _FILE_NAME_H_ #define _FILE_NAME_H_ // public declarations #endif

slide-33
SLIDE 33

To be continued.

This page is not left blank. Intentionally.