sábado, 16 de noviembre de 2013

void-Function & Call-by-Reference vs Call-by-Value

A void-function implement a sub-task that returns no value or more than one value.  Keyword void replaces the type of the value returned.

void Function Declaration Syntax:

void Function_Name(Parameter_List);
Function_Declaration_Comments

void Function Definition Syntax:

void Function_Name(Parameter_List);          <----- Function header
{
Declaration_1
Declaration_2          <--------------- You may intermix the declaration with the executable statements.
. . .
Declaration Last
Executable_Statement_1
Executable_Statement_2
. . .
Executable_Statement_Last          <----------- May or may not include one or more return statements.
}



void-function calls are executable statements that they do not need to be part of another statement. Mechanism is nearly the same as the function calls we have seen.

show_results(32.5, 0.3);

The main function in a program is used like a void function. The return is needed because the main function is defined to return a value of type int. C++ standard say the return 0 can be omitted, but many compilers still require it.

Call-by-Reference vs Call-by-Value
Both store a value.

Call-by-Reference allow us to change the variable used in the function call.  Must be a variables not a numbers.  For example:

void f (int& ref_par);       <----- the '&' symbol identifies f as a call-by-reference parameter.

Call-by-value is not adequate when we need a sub-task to obtain input value.  Means the formal parameters receive the value of the argument.  To input a value, we need to change the variable that are arguments to the functions.  For example:

void f (int var_par);

Precondition: State what is assumed to be true when the function is called.
Postcondition: Describe the effect of the function call.  Tell what will be true after the function is executed.  If they returns a value, that value is described.

For example:

Using precondition and postcondition to declare a swap_value become:

void swap_value(int& n1, int& n2);
//Precondition: variable 1 and variable 2 have been given values
//Postcondition: The value of variable 1 and variable 2 have been interchanged











No hay comentarios.:

Publicar un comentario