Chapter 6 Functions and an Introduction to Recursion

¡Supera tus tareas y exámenes ahora con Quizwiz!

rand

"random" this rand C++ standard library function. The function rand generates an unsigned integer between 0 and RAND_MAX (a symbolic constant defined in the <cstdlib> header). -You can determine the value of RAND_MAX for your system simply by displaying the constant. -If rand truly produces integers at random, every number between 0 and RAND_MAX has an equal chance of being chosen each time rand is called.

golden ratio or golden mean

-This is called the fibonacci numbers. They are the sum of the precious two fibonacci numbers. ex: 0, 1, 1, 2, 3, 5, 8, 13, 21 -they happen in nature! For example, spiral shells, spiral galaxies, wow!

Global variables

-created by placing variable declarations outside any class or function definition. -these retain their values throughout a program's execution -note : global variables should be avoided. in general, variables should be declared in the narrowest scope in which they need to be accessed. Certainly, variables used in a particular function should be declared as local variables in that function rather than as global variables

What does the compiler use the prototype for?

-ensure that maximum's first line (line 20) matches its prototype (line 7) pg. 217 example 6.3 -check that the call to maximum (line 16) contains the correct number and types of arguments, and that the types of the arguments are in the correct order (in this case, all the arguments are of the same type). -ensure that the value returned by the function can be used correctly in the expression that called the function for example, for a function that returns void you cannot call the function on right side of an assignment -ensure that each argument is consistent with the type of the corresponding parameter, for example, a parameters of type double can receive values like 7.35. 22, or-0.03456, but not a string like "hello". If the arguments passed to a function do not match the types specified in the function's prototype, the compiler attempts to convert the arguments to those types.

block scope

-identifiers declared inside a block have block scope, which begins at the identifier's declaration and ends at the terminating right brace ( } ) -local variables have block scope -function parameters have block scope even though they're declared outside the block's braces. Any block can contain variable declarations -note: when blocks are nested and an identifier in an outer block has the same name as an identifier in an inner block, the one in the outer block is "hidden" until the inner block terminates - the inner block sees its own local variable's value and not that of the enclosing block's identically name variable. However, avoid using the same name identifier in an inner block the same as the outer block.

characteristics of reference variables

-must be initialized in their declarations -cannot be reassigned as aliases to other variables -references are constant -all operations performed on the alias -alias is simply another name for the original variable -unless its a reference to a constant, a reference's initializer must be an lvalue (variable name), not a constant or rvalue expression (e.g. the result of a calculation)

function-call stack or program execution stack

-one of the most important mechanisms computer science students need to understand -this data structure working "behind the scenes" supports the function call/return mechanism. -supports creation, maintenance, and destruction of each called function's local variables. -(last in first out) LIFO behavior is exactly what a function needs in order to return the function that called it

What are the reasons one would choose recursion?

-recursive is normally chosen when the recursive approach more naturally mirrors the problem and results in a program that's easier to understand and debug. -the next reason to choose recursive is that an iterative solution may not be apparent when a recursive solution is.

What are the negatives of recursion?

-repeatedly invokes the mechanism , and consequently the overhead, of function calls which can be expensive in both processor time and memory space. -each recursive call causes another copy of the function variables to be created; this can consume considerable memory -iteration normally occurs within a function, so the overhead of repeated function calls and extra memory assignments are ommited.

Give one example using const before a pass-by-reference mechanism would be better than a pass-by-value

-when passing large objects, use a const reference parameter to simulate the appearance and security of pass-by-value and avoid the overhead of passing a copy of the large object. -when a string argument is called, they can be large objects, so the size of the string object degrades an application's performance, using a reference would solve this issue. for example: std : : string getName () const, the above code indicates that a string is returned by value. Changing this to: const std : : string& getName() const the above code indicates that the string should be returned by reference, eliminating the overhead of copying a string.

recursive function

A function that calls itself, either directly or indirectly (through another function) -note that main main should not be called within a program recursively. It's sole purpose is to be the starting point for program execution. -think of it as a math problem -if the function is called with a more complex problem, it typically divides the problem into two conceptual pieces, a piece that the function knows how to do and a piece that it does not know how to do. To make recursion feasible, the latter piece must resemble the original problem but be a slightly simpler or smaller version. this new problem looks like the orignial so the function calls a copy of itself to work on the smaller problem this is referred to as recursive call and it also called the recursion step.

pseudorandom numbers

A number that appears to be random but is generated by a formula. The function rand actually generates these type of numbers.

functional prototype

A prototype that "looks like" and "works like" a production product. Although they are made from prototype materials, these models simulate actual finishes and colors as well as mechanisms. Above is just another type of definition to refer to. Real definition from book: Function prototype describes the maximum function without revealing its implementation. A function prototype is a declaration of a function that tells the compiler the function's name is return type, and the types of its parameters. Ex: int maximum(int x, int y, int z); // function prototype -parameter names in a function prototype are optional (they're ignored by the compiler), but many programmers use these names for documentation purposes.

reference parameter

A reference is a type of C++ variable that acts as an alias to another object or value. Example: int& number -read from left to right is "number is a reference to an int" -mention variable by name (e.g. number) to pass by reference -reference parameter refers to the original variable in the calling function -original variable can be modified directly by the called function -as always, the function prototype and header must agree

function templates

A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. C++ adds two new keywords to support templates: 'template' and 'typename'. The second keyword can always be replaced by keyword 'class'.

default argument

A value that is given to a parameter if the user calling the function or method does not provide that parameter.

global functions

Functions that do not need to be members of a class in order to be understood by c++. They are not members of a class.

return;

In a function that does not return a result, we showed that control returns when the program reaches the function-ending right brace. You also can explicitly return control to the caller by executing the statement.

divide and conquer

This is how you develop and maintain large programs by constructing them from small, simple pieces, or components. You divide and conquer.

What is the template form in C++?

all function template definitions begin with the template keyword, followed by a template parameter list enclosed in angle brackets ( < and > ) . Every parameter in the template parameter list is preceded by the keyword typename or keyword class. The type parameters are placeholders for fundamental types or user-defined types.

Recursive fibonacci definition can be described recursively as follows:

fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2)

static

reference definition: (adj) fixed, not moving or changing, lacking vitality book definition: -local variables also may be declared static -a static local variable retains its value when the function returns to its caller. -the next time the function is called, the static local variable contains the value it had when the function last completed execution. -note : all static local variables of numeric types are initialized to zero by default. -local variables declared as static retain their values even when they're out of scope for example, the function in which they're declared is not executing.

dangling references

references to undefined variables (discarded variables because the function terminated)

How does C++ perform function calls?

stack. Think of a stack as the same as a pile of plates stacked. The plat placed on top is referred to as pushing. Similarly, when a dish is removed from the piles it's normally removed from the top- referred to as popping the dish off. -stacks are known as last in, first out (LIFO) data structures. -last item pushed (inserted on top of plate dishes) on the stack is the first item popped (removed) from the stack.

Function signature or the signature

the portion of a function prototype that includes the name of the function and the types of its arguments. -the function's return type if not part of the function signature.

promotion rules

this indicates the implicit conversions allowed between fundamental types. An int can be converted to a double A double can also be converted to an int, but this narrowing conversion truncates the double's fractional part.

What is the general formula for rand?

type variableName{ShiftingValue + rand() % scalingFactor}; -shiftingValue is equal to the first numbr in the desired range of consecutive integers -scalingFactor is equal to the width of the desired range of consecutive integers Example: unsigned int face{1 + rand() % 6}; -fig.6.7.5

When are random number generators used?

These are used in simulations and security scenarios where predictability is undesired.

What is a comma operator?

The comma operator guarantees that its operands are evaluated left to right. Do not get confused with commas used to separate arguments within a function.

pass-by-value

The parameter-passing mechanism by which a copy of the value of the actual parameter is passed to the called procedure. If the called procedure modifies the formal parameter, the corresponding actual parameter is not affected.

pass-by-reference

The parameter-passing mechanism by which the caller gives the called function the ability to access the caller's data directly and to modify that data. note: pass by reference can weaken security because the called function can corrupt the caller's data. -there is a performance advantage using this parameter passing mechanism

scope

The portion of a program where an identifier can be used is knows as its scope. -for example, when we declare a local variable in a block, it can be referenced only in that block *AND* in blocks nested within that block.

mixed-type expressions

The promotion rules also apply to expressions containing values of two or more data types; such expressions are referred to as mixed-type expressions.

function template specialization

C++ automatically generates separate function template specializations to handle each type of call appropriately.

unary scope resolution ( : : )

C++ provides this to access a global variable when a local variable of the same name is in the scope. int number {7}; //global variable named number int main() { double{10.5}; //local variable named number cout << "Local double value of number = " << number << "\nGlobal int value of number = " << ::number << endl; } local double value = 10.5 global int value of number = 7 -note : always use the unary scope resolution operator when referring to global variables, even when there is no collision with a local variable name. this makes it clear that you're intending to use the global variable rather than the local variable.

nondeterministic random numbers

These are numbers provided by C++11 that's said to be a more secure library of random-number capabilities - a set of random numbers that can't be predicted than rand is.

inline function

Inline function is one of the important feature of C++. So, let's first understand why inline functions are used and what is the purpose of inline function? When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually execute the function's code. This overhead occurs for small functions because execution time of small function is less than the switching time. C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency if it is small. -The syntax for defining the function inline is: inline return-type function-name(parameters) { // function code } Example: #include <iostream> using namespace std; inline int cube(int s) { return s*s*s; } int main() { cout << "The cube of 3 is: " << cube(3) << "\n"; return 0; } //Output: The cube of 3 is: 27 -Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the request for inlining.

What is a parameter in C++?

It is a type followed by an identifier. Ex: int a integer is the type and the a is the identifier

stack frame or activation record

Keep in mind that as each function is called, it may, in turn, call other functions all before any of the functions return. Each function eventually must return control to the function that called it. So somehow the system must keep track of the return addresses that each function needs to return control to the function that called it. -function call stack is the perfect data structure for handling this info. -each time a function calls another function, an entry is pushed onto the stack. This entry called a stack frame or an activation record, contains the return address that the called functions needs in order to return the calling function. -once the called function gets what it needs from the other called functions it needed, it then is referred to as "popped" from there, it control transfers to the return address in the popped stack frame. -note that the return address is placed on top of the stack - with the newly called function, therefore, when the newly called function is done executing, it simply returns control to the return address at the top of the stack. -note that non-static local variables are great to use and are most likely define in certain functions. The called function's stack frame is a perfect place to reserve the memory for the called function's non static local variables. That stack frame exists as long as the called function is active. When the function returns, no longer needs its non static local variables its stack frame is popped from the stack, and those non static local variables no longer exists.

randomizing

Once a program has been thoroughly debugged, it can be conditioned to produce a difference sequence of random numbers for each execution. This is called randomizing.

How does the compiler differentiate among overloaded functions?

Overloaded functions are distinguished by their signatures. A signature is a combo of function's name and its parameter types (in order) . The compiler then encodes each function identifier with the types of its parameters (sometimes referred to as name mangling, or name decoration) to enable type-safe-linkage. Type-safe-linkage ensures the proper overloaded function is called.

function overloading

Process of creating several functions with the same name but different parameter types. Example: int square (int x) cout << "Square of an integer" << x << "is"; return x*x; double square (double y) cout <<"Square of a double" << y << "is"; return y * y; this tells the compiler "hey compiler, if the caller calls a value of an int, choose x definition, but if the caller calls the value of a double, choose y definition.

srand

Seeds the random number generator (rand function) to produce a different sequence of random numbers for each execution. For example, fig 6.8 demonstrates srand. The program produces a different sequence of random numbers each time it executes, provided that the user enters a different "seed."

What is the difference const and static?

Static Variables: Initialized only once. Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor) Value persists between different function calls Const Variables: Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.

scoped enumeration

This is introduced by the keywords enum class, followed by a type name (status) and a set of identifiers representing integer constants. Example: fig. 6.9 line 12 //scoped enumeration with constants that represent the game status enum class status {CONTINUE, WON, LOST}; //all caps in constants -the values in these enumeration constants (CONTINUE, WON, LOST) are of type int, start at 0 (unless specified otherwise) and increment by 1. In the preceding enumeration, the constant CONTINUE has the value 0, WON has the value 1 and LOST has the value 2. -the identifiers in an enum class must be unique, but separate enumeration constants can have the same integer value. -variables of user-defined type Status can be assigned only one of the three values declared in enumeration. -use only uppercase letters in enumeration constant names. This makes these constants stand out in a program and reminds you that enumeration constants are not variables. -use unique values for an enum's constants to help prevent hard-to-find logic errors.

What is the default_random_engine and the uniform_int_distribution?

This is something that evenly distributes pseudorandom integers over a specified range of values. In chapter 6, we are going to use this default random number generation engine. -default range is from 0 to maximum value of an int on your platform.

argument coercion

This is when you force arguments to the appropriate types specified by the parameter declarations. For example, a program can call a function with an integer argument, even though the function prototype specified a double parameter - the function will still work correctly, provided this is not a narrowing conversion.

When are overloaded functions used?

To perform SIMILAR operations that involve DIFFERENT program logic on DIFFERENT data types.

stack overflow

When more function calls occur than can have their activation records stored on the function-call stack, the fatal error, stack overflow, occurs.

What does it mean when you use a function template?

You are then allowed to pass data type as a parameter to a function. Normally, one passes arguments to the already defined parameters, however, function templates do not have already defined parameters, so one can then pass a data type as a parameter to a function.

What is an alias in C++?

a reference variable


Conjuntos de estudio relacionados

chapter 38: bowel elimination PrepU quiz

View Set

Compare and Contrast: Articles of Confederation vs Constitution

View Set

To Kill A Mockingbird: Chapters 8-14

View Set

Apparel and Accessories Marketing

View Set

PrepU Chapter 39: Oxygenation and Perfusion

View Set

Health unit 1 quiz 2 Body systems

View Set

Learning Curve: 13b Anxiety and Substance Use Disorders

View Set