1 / 35

Chapter 8 Scope

Chapter 8 Scope. Dale/Weems/Headington. 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. Alcance (“Scope”) del Enunciado (“Identifier”).

lamar
Download Presentation

Chapter 8 Scope

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8Scope Dale/Weems/Headington

  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

  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. 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 Local Scope vs. Global Scope

  5. const float TAX_RATE = 0.05 ; // global constant floattipRate ; // global variable void handle ( int, float ) ; // function prototype usingnamespace std ; int main ( ) { intage ; // age and bill local to this block floatbill ; .// a, b, and tax cannot be used here .// TAX_RATE and tipRate can be used handle (age, bill) ; return 0 ; } void handle (inta, floatb) { floattax ;// a, b, and tax local to this block . // age and bill cannot be used here .// TAX_RATE and tipRate can be used } 5

  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. Quizz – Determine alcance y valores #include <iostream> usingnamespace std; void SomeFunc (float); const int a = 17; // constante __________ intb; // variable __________ intc; // 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 ______ { floatb; //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. Quizz – Respuestas #include <iostream> usingnamespace std; void SomeFunc (float); const int a = 17; // constante GLOBAL intb; // variable GLOBAL intc; // 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 { floatb; //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. Reglas de Alcances(“Scope”) • Los nombres de funciones tienen alcance global. • El alcance de los parámetros de una función es similar al alcance de las variables locales declaradas en ese bloque. • 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. • 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. • El alcande de un enunciado no incluye bloques internos que contenga enunciados declarados localmente con el mismo nombre. (enunciadoslocales tienen precedencia en el nombre).

  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.

  11. Program with Several Functions function prototypes main function Square function Cube function

  12. Value-returning Functions #include <iostream> int Square( int ) ;// prototypes int Cube( int ) ; usingnamespace 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. 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. float AmountDue (charkind, intcalls)// 2 parameters { floatresult ; // 1 local variable constfloatUNLIM_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. #include <iostream> #include <fstream> float AmountDue ( char, int ) ; // prototype usingnamespace std ; void main ( ) { ifstream myInfile ; ofstream myOutfile ; intareaCode, Exchange, phoneNumber, calls ; intcount = 0 ; floatbill ; charservice ; . . . . . . // open files while ( count < 100 ) { myInfile >> service >> phoneNumber >> calls ; bill=AmountDue (service,calls) ;// function call myOutfile << phoneNumber << bill << endl ; count++ ; } . . . . . .// close files } 16

  17. Para manejar la llamada(“call”)AmountDue(service, calls) MAIN PROGRAM MEMORY Locations: 4000 4002 4006 200 ? ‘U’ calls bill service TEMPORARY MEMORY for function to use 7000 7002 7006 Locations: calls result kind 17

  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

  19. int Power ( /* in */intx ,// Base number /* in */intn )// 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 { intresult ;// Holds intermediate powers of x result = 1; while ( n > 0 ) { result = result * x ; n-- ; } return result ; } Otro ejemplo

  20. “Syntax Template” para una definición de función DataType FunctionName ( Parameter List ) { Statement . . . }

  21. Usando el tipo bool en un ciclo . . . booldataOK ;// declare Boolean variable floattemperature ; . . . dataOK = true ;// initialize the Boolean variable while ( dataOK ) { . . . if ( temperature > 5000 ) dataOK = false ; }

  22. Una Función Boolean bool IsTriangle ( /* in */floatangle1, /* in */floatangle2, /* in */floatangle3 ) // 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. 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

  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

  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. Cuando usar Funciones “Value-Return” • Si se tiene que devolver más de un valor o modificar uno de los argumentos, no utilize funciones “value-return”. • Si tiene que ejecutar un I/O, no utilize funciones “value-return”. • Si solo tienes que devolver un valor y es “Boolean” es apropiado utilizar funciones “value-return”. • Si solo tienes que devolver un valor y se va a usar inmediatamente en una expresión, es apropiado utilizar funciones “value-return”. • 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. • En caso de que cualquier método aplique, utiliza el que más te guste.

  27. ¿ Que hace la función con el argumento? SI LA FUNCIÓN-- FUNCTION PARAMETER IS-- Solo usa su valor Va a dar un valor cambiará su valor /* in */ value parameter /* out */ reference parameter using & /* inout */ reference parameter using & NOTA: I/O “stream variables” y arreglos son excepciones

  28. Programa ConvertDates // ******************************************************* // 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 usingnamespace std; void Get2Digits( ifstream&, string& ); // prototypes void GetYear( ifstream&, string& ); void OpenForInput( ifstream& ); void OpenForOutput( ofstream& ); void Write( ofstream&, string, string, string ); 28

  29. ConvertDates Continuación int main( ) { stringmonth; // Both digits of month stringday; // Both digits of day stringyear;// 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. 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. 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. Structure Chart Main month day year someFile someFile dataIn twoChars dataIn year dataOut Open For Input Get Two Digits Open For Output Get Year Write 32

  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 { chardigitChar ; // One digit of the year intloopCount ; // Loop control variable year = “”; // null string to start loopCount = 1 ; while ( loopCount <= 4 ) { dataIn >> digitChar ; year = year + digitChar ; loopCount++ ; } } 33

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

More Related