lecture 2
play

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


  1. Lecture 2 Struct and Functions

  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

  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

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

  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};

  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};

  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

  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 of 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; }

  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?

  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!!!!

  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

  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.

  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

  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);

  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

  16. Why not just return? • In some cases you need to ”return” several values. – Solve a 2:nd degree polynom (ax 2 +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.

  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’);

  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

  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

  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

  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

  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?

  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)

  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); });

  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); }

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend