1 / 54

The C++ Programming Language

The C++ Programming Language. Declarations and Constant H.J. Kim. Contents. 1. Declarations 2. Declarations 3. Objects and lvalues 4. Lifetime 5. Names 6. Types Overview Fundametal types Derived types void . Pointers

karsen
Télécharger la présentation

The C++ Programming Language

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. The C++ Programming Language • Declarations and Constant • H.J. Kim

  2. Contents • 1. Declarations • 2. Declarations • 3. Objects and lvalues • 4. Lifetime • 5. Names • 6. Types • Overview • Fundametal types • Derived types • void

  3. Pointers • Arrays • Structures • Type equalency • Reference • 7. Literals • 8. Named constraints • const v.s macro • Enumerations • 9. Fields • 10. Unions

  4. Declarations • Informs the compiler with • 1. Name and • 2. Type • char ch; // declaration & definition • char* name = "OOPSLA"; // declaration efinition • extern complex sqrt(complex); //declaration • typedef complex point; // declaration • struct user; // declaration

  5. Notes • Declaration + object allocation = definition • Exactly one definition for each name, but may many declarations

  6. Scopes • Declaration introduces a name into a scope • A declaration of a name in a block can hide a declaration in an enclosing block or a blobal name • cf) hidden global name can be used by using “::''

  7. Function argument naes are considered declared in the outermost block of a function • int x; // global x • void f() • { • int x; // local x hides global x • x = 1; // assign to local x • { • int x; // hides first local x • x = 2; // assign to second local x • ::x = x; // assign to global x • } • x = 3; to first local x • }

  8. Notes • Scope rule in C++ • A name declared in a function (local name) • from the point of declaration to the end of the block in which its declaration occurs • A name not in a function or in a class (= global name) • from the point of declaration to the end of the file in which its declaration occurs

  9. Objects and Lvalues • Object : a region of storage • Lvalue: an expression referring to an object or a function • int i, j; • i = j = 10; // lvalue: i, j

  10. Lifetime • The time during objects' existence • Default lifetime • Objects with local names are created when its definition is encountered and destroyed when its name goes out of scope • Objects with global names are created and initialized once and live until the program terminates

  11. Local objects with the keyword ``static'' live until the end of the program • f() • { • static int i; • // ..... • } • Notice : “i” cannot be accessed outside f()!! • Using the “new” and “delete” operators, • user-controlled-lifetime objects can be created

  12. NAMES • A name consists of a sequence of letters and digits • The first character must be a letter • C++ imposes no limit on the number of characters in a name, but some implementations do

  13. Notes • Names starting with underscore are reserved for special facilities therefore, avoid them as much as possible • hello this_is_a_most_unusually_long_name • _Class • ___

  14. Types: Overview • Every name in a C++ program has a type associated with it • C++ is strongly-typed language • Type determines ...... • what operations can be applied to the name • how such operations are interpreted • (cf. operatoroverloading)

  15. The only operators can be applied to type name are: • sizeof : determining the amount of memory required to hold an object of the type • new : free-store allocation of objects of the type

  16. A type name can be used for explicite type conversion • float f; • char* p; • ................ • long ll = long(p); // convert p to a long • int i = int(f); // convert f to an int

  17. Types : Fundamental Types • Basic integer types • char • short int • int • long int • enumerate • float • double • long double

  18. Unsigned integers, logical values, bit arrays, etc. can be represented by the keyword ``unsigned'' • Signed types can be represented by the keyword ``signed'' • In general, when a type is missing in a declaration, ``int'' is assumed • Some guaranteed facts for compiler (implementation)

  19. Notes • 1 = sizeof(char) <= sizeof(short) <=sizeof(int) <=sizeof(long) • sizeof(float) <= sizeof(double) <= sizeof(long double) • sizeof(I) = sizeof(signed I) = sizeof(unsigned I) • . I = basic integer type • |char| >= 8 , |short| >= 16 , |long| >= 32

  20. Types : Implicit Type Conversion • Integral promotion • enum Baseballteamtype • { TWINS, GIANTS, BEARS, LIONS, TIGERS, EAGLES, DOLPHIN }; • Baseballteamtype winner = TWINS; • int i = winner; // integral promotion from enum • // to int, i == 0

  21. Integral conversion • int i = -1; • unsigned int j = 10; • j = i; // integral conversion from int • // to unsigned int • i = j; // integral conversion from unsigned • // to signed int

  22. Notes • Integral promotion • From char, short int, enum,or int bit-field to int • If an int can represent all values of the original type, the value is converted to int • ; otherwise it is converted to unsigned int

  23. Integral conversion • integer =>unsigned integer : • the value is the least integer congruent to the signed integer • unsigned integer => signed integer : • the value is unchanged if it can be represented in the new type • ; otherwisethe value is implementation dependent

  24. Types : Implicit Type Conversion (cont'd) • Float and Double • float x = 10.0; • double y = x; // conversion from float to double • x = y; // conversion from double to float • Floating and Integral • int i = 100; • float x = i; // conversion int to float • i = x; // conversion float to int

  25. Notes • Float and Double • float -> double : • the value is unchanged • double -> float : • if the value with inrepresentable range, the result may be either the next higher or the next lower representable value; • otherwise the behavior is undefined

  26. Floating and Integral • floating -> integral value: • the fractional part is discarded and such conversions are machine dependent • integral -> floating type: • loss of precision occurs if an integral value cannot be represented exactly as a value of the floating type • etc.

  27. Types : Derived Types • New types can be derived by using the declaration operators • * : pointer • & : reference • [] : array • (): function • and the structure definition mechanism • (eg. struct})

  28. When declaring derived types, note that declaration operators apply to the very next individual name only • int v[10]; • int *p; • int *v[10], (*p)[10]; • int* p, y; // same as int* p; \ int y;

  29. Types : void • Usages : • 1. Specify that a function does not return a value • 2. The base type for pointers to objects of unknown type • void f(); // f does not return a value • void* pv; // pointer to object of unknown type

  30. void* malloc(unsigned size); void free(void*); void f() // C style allocation { int* pi = (int*)malloc(10*sizeof(int)); char* pc = (char*)malloc(10); //................. free(pi); free(pc); }

  31. Notes • A pointer of any type can be assigned to a value of type void* • 1.For passing pointers to functions that are not allowed to make assumptions about the type of the object • 2. For returning untyped objects from functions

  32. Types : Pointers • For most types T, T* is the type pointer to T int *pi; char** cpp; // pointer to pointer to char int (*vp)[4]; // pointer to array of 4 ints int (*fp)(char,char*); // pointer to function // taking (char, char*) arguments // and return an int

  33. Notes pi 123 cpp ‘a’ vp 123 234 456 678 fp function code for int f(char,char*)

  34. Types : Arrays • For a type T,T[size] is the type “array of size • elements of type T” • Elements are indexed from 0 to size-1 • float v[3]; • int a[2][5]; • char* vpc[32]; // array of 32 character pointers • The name of an array can also be used as a pointer to its first element • int v[5] = {1, 2, 3, 4, 5}; • int i = *v // assign v[0] to i

  35. If p is assumed to point to an element of an array: • p+1 means the next element of that array • p-1 means the previous element of that array #include <iostream.h> int v[5] = {1, 2, 3, 4, 5}; int* vp = &(v[2]); cout << *vp; // value of v[2] is printed cout << *(vp+1); // value of v[3] is printed cout << *(vp-1); // value of v[1] is printed

  36. Notes • Only substraction between pointes is allowed. • -> conversion needed • void *p = &aa; • void *q = p + 10;

  37. Types : Structures • A structure is an aggregate of elements of arbitrary types • struct address { • char* name;}; • The individual member can be accessed using . operator or -> operator • address ad; • address* adp = &ad; • ad.name = "Jim Dandy"; • adp->number = 61;

  38. The name of a type becomes available for use immediately after it has been encountered, and not just after the complete declaration has been seen • struct link { • link* prev; • link* succ; • };

  39. Notes ad adp ad.name = “Jim Dandy” adp->number = 0 name number ad adp “Jim Dandy” name number

  40. Types : Type Equalency • Two structure types even when they have the same members • struct s1 {int a;}; • struct s2 {int a;}; • s1 x; • s2 y = x; // error: type mismatch • Structure types are different from fundamental types • s1 x; • int i = x; // error: type mismatch

  41. A declaration prefixed by the keyword “typedef” declares a new name for the type • typedef char* Pchar; • Pchar p1; • char* p3 = p1;

  42. Types: Reference • For a type T, T& means reference to T • A reference must be initialized • int i = 1; • int& r = i; // r and i now refer to the same int • For a type T, the initializer for a const T& need • not be an lvalue or even of type T • double& dr = 1; // error: lvalue needed • const double& cdr = 1; // ok • References can be used for call-by-reference in parameter passing

  43. Notes i j,r 1 1 char ch; char ch; char *p = &ch; char &r = ch; *p = ‘a’; r = ‘a’ ; ch p r,ch ‘a’ ‘a’

  44. Literals • Integer constants • The type of a decimal constant is int provided it fits into an int; otherwise, it is long • Suffix U : unsigned constant • Suffix L : long constant • 1234 077 0x3f 3U 3L • Floating-point constants • A floating-point constant is of type double • Suffix f : floating-point constant of type float • 1.23 .23 1. 1.2e10 2.0f

  45. Character constants • A character constant is a character enclosed in single quotes • It is possible to represent a character as a one-, • two-, or three-digit octal number ( \ followed by octal digits), or as a hexadecimal number ( \x followed by hexadecimal digits) • A few characters also have standard names that use backslash \ as an escape character • 'a' '\6' '\x5f' '\n' '\t'

  46. Notes • String literals • A string literals is a character sequence enclosed in double quotes • The type of string is “array of the appropriate • number of characters'' • "this is a string" • Zeros • 0 is an int • Because of standard conversion, 0 can be usedas a constant of any integer, floating point, or pointer type

  47. Named Constants • The keyword const can be added to the declaration of an object to make that object a constant • A constant must be initialized • const int model = 90; • const int v[] = {1, 2, 3, 4};

  48. When using pointer types: • 1.the object pointed to: prefixing a declaration of a pointer with const • const char* pc = "asdf"; // pointer to constant • pc[3] = 'a'; // error • pc = "ghjk"; // ok • 2. the pointer itself: operator *const is used • char *const cp = "asdf"; // constant pointer • cp[3] = 'a'; // ok • p = "ghjk"; // error

  49. Notes pc cp “asdf” “asdf” fixed fixed “asdf” pc cp “ghjk” “asdf” v.s.

  50. Named Constants : const v.s #defined Macro • Macro is processed in preprocessor, not in complier. • Macro statement is not C++ statement • => no macro statement needs ‘;’ • => two kind of statement in a program • cf) embedded SQL in a host program • can't show uniform view to the programmer • #define MAXLEN 10 • const int MAXLEN= 10;

More Related