Presentation is loading. Please wait.

Presentation is loading. Please wait.

The C++ Programming Language Declarations and Constant H.J. Kim.

Similar presentations


Presentation on theme: "The C++ Programming Language Declarations and Constant H.J. Kim."— Presentation transcript:

1 The C++ Programming Language Declarations and Constant H.J. Kim

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

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

4 Declarations u 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 u Declaration + object allocation = definition u Exactly one definition for each name, but may many declarations

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

7 u 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 u Scope rule in C++ u A name declared in a function (local name) þ from the point of declaration to the end of the block in which its declaration occurs u A name not in a function or in a class (= global name) þ from the point of declaration to the end ofthe file in which its declaration occurs

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

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

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

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

13 Notes u 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 u Every name in a C++ program has a type associated with it þ C++ is strongly-typed language u Type determines...... u what operations can be applied to the name u how such operations are interpreted (cf. operatoroverloading)

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

16 u 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 u Basic integer types u char u short int u int u long int u enumerate u float u double u long double

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

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

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

21 u 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 u Integral promotion u From char, short int, enum,or int bit-field to int u 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 u Integral conversion u integer =>unsigned integer : the value is the least integer congruent to the signed integer u 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) u Float and Double float x = 10.0; double y = x; // conversion from float to double x = y; // conversion from double to float u Floating and Integral int i = 100; float x = i; // conversion int to float i = x; // conversion float to int

25 Notes u Float and Double u float -> double : the value is unchanged u 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 u Floating and Integral u floating -> integral value: the fractional partis discarded and such conversions are machine dependent u integral -> floating type: loss of precision occurs if an integral value cannot be represented exactly as a value of the floating type u etc.

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

28 u 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 u 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 u A pointer of any type can be assigned to a value of type void* u 1.For passing pointers to functions that are not allowed to make assumptions about the type of the object u 2. For returning untyped objects from functions

32 Types : Pointers u 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 cpp vp fp 123 ‘a’ function code for int f(char,char*) 123 234 456 678

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

35 u If p is assumed to point to an element of an array: u p+1 means the next element of that array u p-1 means the previous element of that array #include 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 u Only substraction between pointes is allowed. -> conversion needed void *p = &aa; void *q = p + 10;

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

38 u 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 adp ad name number adp ad name number “Jim Dandy” ad.name = “Jim Dandy” adp->number = 0

40 Types : Type Equalency u 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 u Structure types are different from fundamental types s1 x; int i = x; // error: type mismatch

41 u 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 u For a type T, T& means reference to T u A reference must be initialized int i = 1; int& r = i; // r and i now refer to the same int u For a type T, the initializer for a const T& need u not be an lvalue or even of type T double& dr = 1; // error: lvalue needed const double& cdr = 1; // ok u References can be used for call-by-reference in parameter passing

43 Notes 11 ij,r ‘a’ p ch r,ch ‘a’ char ch; char *p = &ch; char &r = ch; *p = ‘a’; r = ‘a’ ;

44 Literals u 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 u 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 u Character constants u A character constant is a character enclosed in single quotes u It is possible to represent a character as a one-, u two-, or three-digit octal number ( \ followed by octal digits), or as a hexadecimal number ( \x followed by hexadecimal digits) u A few characters also have standard names that use backslash \ as an escape character 'a' '\6' '\x5f' '\n' '\t'

46 Notes u 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" u Zeros u 0 is an int u Because of standard conversion, 0 can be usedas a constant of any integer, floating point, or pointer type

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

48 u 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 “asdf” “ghjk” “asdf” pc cp “asdf” cp fixed v.s.

50 Named Constants : const v.s #defined Macro u Macro is processed in preprocessor, not in complier. u 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;

51 u const gives more type information u Macro is just text substitution, but const isn't #define NUM1 2 + 2 const int NUM2= 2 + 2; void main() { int i = NUM1 * 2; // set i with 6 int j = NUM2 * 2; // set j with 8 // - it's our intention }

52 Named Constants : Enumerations u Alternative method for naming integer constants enum { ASM, AUTO, BREAK }; u Values can also be explicitly given to enumerators enum int16 { sign = 010000, most_significant = 04000, least_significant = 1 };

53 Fields u Bundling several tiny variables together in a struct u Saves data space, but the size of the code needed to manipulate these variables increases struct sreg { unsigned int enable : 1; unsigned int page : 3; unsigned int : 1; // unused unsigned int mode : 2; unsigned int : 4; // unused unsigned int access : 1; unsigned int length : 1; unsigned int non_resident : 1; };

54 Unions u Used when members are not used simultan- eously struct entry { char* name; char type; union { char* string_value; int int_value; };


Download ppt "The C++ Programming Language Declarations and Constant H.J. Kim."

Similar presentations


Ads by Google