Descargar la presentación
La descarga está en progreso. Por favor, espere
Publicada porMarita Canino Modificado hace 10 años
1
1 Chapter 8 Scope Dale/Weems/Headington
2
2 Tópicos del Capítulo 8 l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine which Variables are Accessible in a Block l Writing a Value-Returning Function for a Task
3
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
4
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
5
5 const float TAX_RATE = 0.05 ; // global constant float tipRate ;// global variable void 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
6
6 Alcance de una variable Global int 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 : }
7
7 Quizz – Determine alcance y valores #include 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: ______ }
8
8 Quizz – Respuestas #include using namespace std; void SomeFunc (float); const int a = 17;// constante GLOBAL int b;// variable GLOBAL int c;// variable LOCAL int main() { b = 4;// Se asigna a b GLOBAL c = 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 GLOBAL b = 2.3;//Asigna a b LOCAL cout << “a = “ << a;// El Output es: 17 cout << “b = “ << b;// El Output es: 2.3 cout << “c = “ << c;// El Output es: 42.8 }
9
9 Reglas de Alcances(“Scope”) 1Los nombres de funciones tienen alcance global. 2El alcance de los parámetros de una función es similar al alcance de las variables locales declaradas en ese bloque. 3El 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. 3El 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. 5El alcande de un enunciado no incluye bloques internos que contenga enunciados declarados localmente con el mismo nombre. (enunciados locales tienen precedencia en el nombre).
10
10 Precedencia de Nombres, según el Compilador l Cuando una expresión se refiere a un enunciado, el compilador primero coteja las declaraciones locales. l 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. l Cualquier enunciado con el mismo nombre declarado en un nivel superior no se considera. l Si el compilador llega a las declaraciones globales y aún no encuentra el enunciado, da un mensaje de error.
11
11 Program with Several Functions Square function Cube function function prototypes main function
12
Value-returning Functions #include int Square ( int ) ; // prototypes int 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
13
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
14
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.
15
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
16
16 #include float AmountDue ( char, int ) ; // prototype using 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 call myOutfile << phoneNumber << bill << endl ; count++ ; }...... // close files } 16
17
17 Para manejar la llamada(“call”) AmountDue(service, calls) MAIN PROGRAM MEMORY TEMPORARY MEMORY for function to use Locations: calls bill service calls result kind 4000 4002 4006 7000 7002 7006 200?‘U’ 17
18
18 Manejando el “Function Call” bill = AmountDue(service, calls); l Comienza evaluando cada argumento l Una copia del valor de cada uno es enviado a una memoria temporera creada para eso l El cuerpo de la función determina el resultado l El resultado se devuelve y se asigna a la variable bill
19
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
20
20 “Syntax Template” para una definición de función DataType FunctionName ( Parameter List ) { Statement. }
21
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 ; }
22
22 Una Función Boolean bool 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 ) ; }
23
23 Algunos Prototipos del Header File 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
24
24 Algunos Prototipos del Header File 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
25
25 ¿“Qué hace la función con el argumento?” La contestación la determina si el parámetro de la función es por valor o por referencia… Ejemplo…..
26
26 Cuando usar Funciones “Value-Return” 1Si se tiene que devolver más de un valor o modificar uno de los argumentos, no utilize funciones “value-return”. 2Si tiene que ejecutar un I/O, no utilize funciones “value- return”. 3Si solo tienes que devolver un valor y es “Boolean” es apropiado utilizar funciones “value-return”. 4Si solo tienes que devolver un valor y se va a usar inmediatamente en una expresión, es apropiado utilizar funciones “value-return”. 5Cuando 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. 6En caso de que cualquier método aplique, utiliza el que más te guste.
27
27 /* in */ value parameter /* out */ reference parameter using & /* inout */ reference parameter using & ¿ 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
28
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 // for cout and endl #include // for setw #include // for file I/O #include // for string type using namespace std; void Get2Digits( ifstream&, string& ); // prototypes void GetYear( ifstream&, string& ); void OpenForInput( ifstream& ); void OpenForOutput( ofstream& ); void Write( ofstream&, string, string, string ); Programa ConvertDates 28
29
29 ConvertDates Continuación int 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;
30
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; }
31
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
32
Get YearWrite Structure Chart Main Get Two Digits Open For Output Open For Input someFile dataIntwoCharsdataOutyeardataIn month day year 32
33
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
34
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.
35
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” ; }
Presentaciones similares
© 2025 SlidePlayer.es Inc.
All rights reserved.