35
1 Chapter 8 Scope Dale/Weems/Headington

1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

Embed Size (px)

Citation preview

Page 1: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

1

Chapter 8

Scope

Dale/Weems/Headington

Page 2: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

2

Tópicos del Capítulo 8

Local Scope vs. Global Scope of an Identifier

Detailed Scope Rules to Determine which Variables are Accessible in a Block

Writing a Value-Returning Function for a Task

Page 3: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

3

Alcance (“Scope”) del Enunciado (“Identifier”)

El alcance de un enunciado es la región del código del

programa en donde es legal utilizar ese enunciado para

algún propósito

Page 4: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

4

Local Scope vs. Global Scope

El alcance de un enunciado que se declara dentro de un bloque (incluyendo los parámetros) se extiende desde el punto de declaración hasta el final del bloque

El alcance de un enunciado que se declara fuera de un bloque se extiende desde el punto de declaración hasta el final del código del programa

Page 5: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

5

const float TAX_RATE = 0.05 ; // global constantfloat tipRate ; // global variablevoid handle ( int, float ) ; // function prototype

using namespace std ;

int main ( ){ int age ; // age and bill local to this block float bill ; . // a, b, and tax cannot be used here . // TAX_RATE and tipRate can be used handle (age, bill) ;

return 0 ;}

void handle (int a, float b){ float tax ; // a, b, and tax local to this block . // age and bill cannot be used here . // TAX_RATE and tipRate can be used} 5

Page 6: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

6

Alcance de una variable Globalint gamma; // variable global

int main(){

gamma = 3; // Se puede usar en la función main :}Void SomeFunc(){gamma = 5; // y también en la función SomeFunc :}

Page 7: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

7

Quizz – Determine alcance y valores#include <iostream>using namespace std;void SomeFunc (float);const int a = 17; // constante __________int b; // variable __________int c; // variable __________

int main(){

b = 4; // Se asigna a b _______c = 6; // Se asigna a c _______SomeFunc ( 42.8 )return 0;

}void SomeFunc ( float c ) //Previene acceso a c ______{

float b; //Previene acceso a b ______b = 2.3; //Asigna a b _____cout << “a = “ << a; // El Output es: ______cout << “b = “ << b; // El Output es: ______cout << “c = “ << c; // El Output es: ______

}

Page 8: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

8

Quizz – Respuestas#include <iostream>using namespace std;void SomeFunc (float);const int a = 17; // constante GLOBALint b; // variable GLOBALint c; // variable LOCAL

int main(){

b = 4; // Se asigna a b GLOBALc = 6; // Se asigna a c GLOBAL SomeFunc ( 42.8 )return 0;

}void SomeFunc ( float c ) //Previene acceso a c GLOBAL{

float b; //Previene acceso a b GLOBALb = 2.3; //Asigna a b LOCALcout << “a = “ << a; // El Output es: 17cout << “b = “ << b; // El Output es: 2.3cout << “c = “ << c; // El Output es: 42.8

}

Page 9: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

9

Reglas de Alcances(“Scope”)1 Los nombres de funciones tienen alcance global.2 El alcance de los parámetros de una función es

similar al alcance de las variables locales declaradas en ese bloque.

3 El alcance de una variable o constante global se extiende desde su declaración hasta el final del código. La excepción se menciona en la regla 5.

3 El alcance de una variable o constante local se extiende desde su declaración hasta el final del bloque. Esta incluye cualquier bloque interno menos lo que se menciona en la regla 5.

5 El alcande de un enunciado no incluye bloques internos que contenga enunciados declarados localmente con el mismo nombre. (enunciados locales tienen precedencia en el nombre).

Page 10: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

10

Precedencia de Nombres, según el Compilador

Cuando una expresión se refiere a un enunciado, el compilador primero coteja las declaraciones locales.

Si el enunciado no es local, el compilador coteja el próximo nivel (“nesting”) hasta que encuentre el enunciado con el mismo nombre. Entonces se detiene en la búsqueda.

Cualquier enunciado con el mismo nombre declarado en un nivel superior no se considera.

Si el compilador llega a las declaraciones globales y aún no encuentra el enunciado, da un mensaje de error.

Page 11: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

11

Program with Several Functions

Square function

Cube function

function prototypes

main function

Page 12: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

Value-returning Functions

#include <iostream>

int Square ( int ) ; // prototypesint Cube ( int ) ;using namespace std;

int main ( ){ cout << “The square of 27 is “

<< Square (27) << endl; // function call cout << “The cube of 27 is “ << Cube (27) << endl; // function call

return 0;}

12

Page 13: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

Rest of Program

int Square ( int n ) // header and body{ return n * n;}

int Cube ( int n ) // header and body{ return n * n * n;}

13

Page 14: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

14

Prototipo para una función float

Llamada AmountDue( ) con 2 parámetros

El primero es tipo char, el otro es tipo int.

float AmountDue ( char, int ) ;

Esta función va a encontrar y devolver la cantidad vencida de llamadas de teléfono local. El valor tipo char ‘U’ o ‘L’ indican servicio “Unlimited” o “Limited”, y el int contiene el número de llamadas hechas.

Se asume que un “Unlimited service” es $40.50 por mes.

“Limited service” es $19.38 hasta 30 llamadas, y $.09 por cada llamada adicional.

Page 15: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

15

float AmountDue (char kind, int calls) // 2 parameters{ float result ; // 1 local variable

const float UNLIM_RATE = 40.50, LIM_RATE = 19.38, EXTRA = .09 ;

if (kind ==‘U’) result = UNLIM_RATE ; else if ( ( kind == ‘L’ ) && ( calls <= 30) ) result = LIM_RATE ; else result = LIM_RATE + (calls - 30) * EXTRA ; return result ;} 15

Page 16: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

16

#include <iostream>#include <fstream>float AmountDue ( char, int ) ; // prototypeusing namespace std ;

void main ( ){ ifstream myInfile ; ofstream myOutfile ; int areaCode, Exchange, phoneNumber, calls ; int count = 0 ; float bill ; char service ; . . . . . . // open files while ( count < 100 ) { myInfile >> service >> phoneNumber >> calls ;

bill = AmountDue (service, calls) ; // function callmyOutfile << phoneNumber << bill << endl ;

count++ ; } . . . . . . // close files} 16

Page 17: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

17

Para manejar la llamada(“call”)AmountDue(service, calls)

MAIN PROGRAM MEMORY

TEMPORARY MEMORY for function to use

Locations:

Locations:

calls bill service

calls result kind

4000 4002 4006

7000 7002 7006

200 ? ‘U’

17

Page 18: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

18

Manejando el “Function Call”

bill = AmountDue(service, calls);

Comienza evaluando cada argumento

Una copia del valor de cada uno es enviado a una memoria temporera creada para eso

El cuerpo de la función determina el resultado

El resultado se devuelve y se asigna a la variable bill

Page 19: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

19

int Power ( /* in */ int x , // Base number /* in */ int n ) // Power to raise base to

// This function computes x to the n power

// Precondition:// x is assigned && n >= 0 && (x to the n) <= INT_MAX// Postcondition:// Function value == x to the n power

{ int result ; // Holds intermediate powers of x result = 1; while ( n > 0 ) { result = result * x ;

n-- ; } return result ;}

Otro ejemplo

Page 20: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

20

“Syntax Template” para una definición de función

DataType FunctionName ( Parameter List )

{

Statement...

}

Page 21: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

21

Usando el tipo bool en un ciclo

. . .bool dataOK ; // declare Boolean variable

float temperature ;

. . .dataOK = true ; // initialize the Boolean

variable

while ( dataOK )

{ . . .

if ( temperature > 5000 )

dataOK = false ;

}

Page 22: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

22

Una Función Booleanbool IsTriangle ( /* in */ float angle1,

/* in */ float angle2, /* in */ float angle3 )

// Function checks if 3 incoming values add up to 180 degrees, // forming a valid triangle// PRECONDITION: angle1, angle2, angle 3 are assigned// POSTCONDITION: // FCTNVAL == true, if sum is within 0.000001 of // 180.0 degrees// == false, otherwise{

return ( fabs( angle1 + angle2 + angle3 - 180.0 ) < 0.000001 ) ;

}

Page 23: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

23

Algunos Prototipos del Header File < cctype >

int isalpha (char ch); // FCTNVAL == nonzero, if ch is an alphabet letter

// == zero, otherwise

int isdigit ( char ch); // FCTNVAL == nonzero, if ch is a digit ( ‘0’ - ‘9’)

// == zero, otherwise

int islower ( char ch );// FCTNVAL == nonzero, if ch is a lowercase letter (‘a’ - ‘z’)

// == zero, otherwise

int isupper ( char ch);// FCTNVAL == nonzero, if ch is an uppercase letter (‘A’ - ‘Z’)

// == zero, otherwise

23

Page 24: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

24

Algunos Prototipos del Header File < cmath >

double cos ( double x ); // FCTNVAL == trigonometric cosine of angle x radians

double exp ( double x ); // FCTNVAL == the value e (2.718 . . .) raised to the power x

double log ( double x );// FCTNVAL == natural (base e) logarithm of x

double log10 ( double x );// FCTNVAL == common (base 10) logarithm of x

double pow ( double x, double y );// FCTNVAL == x raised to the power y

Page 25: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

25

¿“Qué hace la función con el argumento?”

La contestación la determina si el parámetrode la función es por valor o por referencia…Ejemplo…..

Page 26: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

26

Cuando usar Funciones “Value-Return”1 Si se tiene que devolver más de un valor o modificar uno de

los argumentos, no utilize funciones “value-return”.

2 Si tiene que ejecutar un I/O, no utilize funciones “value-return”.

3 Si solo tienes que devolver un valor y es “Boolean” es apropiado utilizar funciones “value-return”.

4 Si solo tienes que devolver un valor y se va a usar inmediatamente en una expresión, es apropiado utilizar funciones “value-return”.

5 Cuando tengas dudas, utiliza una función void. Es fácil recodificar una función void con tan solo incluir un nuevo parámetro, pero una función que devuelva un valor, es más dificil de modificar.

6 En caso de que cualquier método aplique, utiliza el que más te guste.

Page 27: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

27

/* in */ value parameter

/* out */ reference parameterusing &

/* inout */ reference parameterusing &

¿ Que hace la función con el argumento?

Solo usa su valor

Va a dar un valor

cambiará su valor

SI LA FUNCIÓN-- FUNCTION PARAMETER IS--

NOTA: I/O “stream variables” y arreglos son excepciones

Page 28: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

28

// ******************************************************* // ConvertDates program// This program reads dates in American form: mm/dd/yyyy// from an input file and writes them to an output file // in American, British: dd/mm/yyyy, and ISO: yyyy-mm-dd// formats. No data validation is done on the input file.// *******************************************************

#include <iostream> // for cout and endl#include <iomanip> // for setw#include <fstream> // for file I/O#include <string> // for string type

using namespace std;

void Get2Digits( ifstream&, string& ); // prototypesvoid GetYear( ifstream&, string& ); void OpenForInput( ifstream& ); void OpenForOutput( ofstream& ); void Write( ofstream&, string, string, string );

Programa ConvertDates

28

Page 29: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

29

ConvertDates Continuaciónint main( ){ string month; // Both digits of month string day; // Both digits of day string year; // Four digits of year ifstream dataIn; // Input file of dates ofstream dataOut; // Output file of dates OpenForInput(dataIn); OpenForOutput(dataOut);

// Check files if ( !dataIn || !dataOut )

return 1; // Write headings

dataOut << setw(20) << “American Format” << setw(20) << “British Format” << setw(20) << “ISO Format” << endl << endl;

Page 30: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

30

Final del main

Get2Digits( dataIn, month ) ; // Priming read

while ( dataIn ) // While last read successful {

Get2Digits( dataIn, day ); GetYear( dataIn, year ); Write( dataOut, month, day, year ); Get2Digits( dataIn, month ); // Read next data

}

return 0; }

Page 31: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

31

Ejemplo del Archivo de Datos de “Input”

10/11/1975

1 1 / 2 3 / 1 9 2 6

5/2/2004

05 / 28 / 1965

7/ 3/ 19 56

Page 32: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

Get Year Write

Structure Chart

Main

Get TwoDigits

Open ForOutput

Open ForInput

someFile someFile dataIn twoChars dataOutyeardataIn

monthdayyear

32

Page 33: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

33

void GetYear ( /* inout */ ifstream dataIn, /* out */ string& year )

// Function reads characters from dataIn and returns four digit

// characters in the year string.

// PRECONDITION: dataIn assigned

// POSTCONDITION: year assigned

{

char digitChar ; // One digit of the year

int loopCount ; // Loop control variable

year = “”; // null string to start

loopCount = 1 ;

while ( loopCount <= 4 )

{

dataIn >> digitChar ;

year = year + digitChar ;

loopCount++ ;

}

} 33

Page 34: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

34

Utilize un “Stub”al probar el programa

Un “stub” es una función “dummy” con un bloque bien corto y sencillo, casi siempre un enunciado de salida (cout) y devuelve un valor de ser necesario. Su nombre y parametros son los mismos de la función original que se está probando.

Page 35: 1 Chapter 8 Scope Dale/Weems/Headington. 2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine

35

Un “Stub”para la función GetYear

void GetYear ( /* inout */ ifstream dataIn,

/* out */ string& year )

// Stub to test GetYear function in ConvertDates program.

// PRECONDITION: dataIn assigned

// POSTCONDITION: year assigned

{

cout << “GetYear was called. Returning \”1948\”.” << endl ;

year = “1948” ;

}