the c++ programming language

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

Upload: karsen

Post on 15-Jan-2016

64 views

Category:

Documents


0 download

DESCRIPTION

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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: The C++ Programming  Language

The C++ Programming The C++ Programming LanguageLanguage

Declarations and Constant

H.J. Kim

Page 2: The C++ Programming  Language

ContentsContents 1. Declarations 2. Declarations 3. Objects and lvalues 4. Lifetime 5. Names 6. Types

Overview Fundametal types Derived types void

Page 3: The C++ Programming  Language

Pointers Arrays Structures Type equalency Reference 7. Literals

8. Named constraints const v.s macro Enumerations

9. Fields 10. Unions

Page 4: The C++ Programming  Language

DeclarationsDeclarations

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

Page 5: The C++ Programming  Language

NotesNotes

Declaration + object allocation = definition Exactly one definition for each name, but m

ay many declarations

Page 6: The C++ Programming  Language

ScopesScopes

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 “::''

Page 7: The C++ Programming  Language

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

}

Page 8: The C++ Programming  Language

NotesNotes

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

Page 9: The C++ Programming  Language

Objects and LvaluesObjects 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

Page 10: The C++ Programming  Language

LifetimeLifetime

The time during objects' existence Default lifetime

Objects with local names are created when its

definition is encountered and destroyed when i

ts name goes out of scope

Objects with global names are created and ini

tialized once and live until the program termina

tes

Page 11: The C++ Programming  Language

Local objects with the keyword ``static'' live un

til 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

Page 12: The C++ Programming  Language

NAMESNAMES

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

Page 13: The C++ Programming  Language

NotesNotes

Names starting with underscore are reserved for special facilities therefore, avoid them as much as possible

hello this_is_a_most_unusually_long_nam

e

_Class

___

Page 14: The C++ Programming  Language

Types: OverviewTypes: 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)

Page 15: The C++ Programming  Language

The only operators can be applied to typ

e name are:

sizeof : determining the amount of memor

y required to hold an object of the type

new : free-store allocation of objects of th

e type

Page 16: The C++ Programming  Language

A type name can be used for explicite ty

pe conversion float f; char* p; ................ long ll = long(p); // convert p to a long int i = int(f); // convert f to an int

Page 17: The C++ Programming  Language

Types : Fundamental TypesTypes : Fundamental Types Basic integer types

char short int int long int

enumerate float double long double

Page 18: The C++ Programming  Language

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)

Page 19: The C++ Programming  Language

NotesNotes

1 = sizeof(char) <= sizeof(short) <=sizeof(int) <=

sizeof(long)

sizeof(float) <= sizeof(double) <= sizeof(long d

ouble)

sizeof(I) = sizeof(signed I) = sizeof(unsigned I)

. I = basic integer type

|char| >= 8 , |short| >= 16 , |long| >= 32

Page 20: The C++ Programming  Language

Types : Implicit Type ConversionTypes : 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

Page 21: The C++ Programming  Language

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

Page 22: The C++ Programming  Language

NotesNotes

Integral promotion

From char, short int, enum,or int bit-field to int If an int can represent all values of the original ty

pe, the value is converted to int ; otherwise it is converted to unsigned int

Page 23: The C++ Programming  Language

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 represente

d in the new type ; otherwisethe value is implementation depend

ent

Page 24: The C++ Programming  Language

Types : Implicit Type Conversion (cont'd)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

Page 25: The C++ Programming  Language

NotesNotes

Float and Double float -> double :

the value is unchanged

double -> float : if the value with inrepresentable range, the result ma

y be either the next higher or the next lower representable value;

otherwise the behavior is undefined

Page 26: The C++ Programming  Language

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 re

presented exactly as a value of the floating type

etc.

Page 27: The C++ Programming  Language

Types : Derived TypesTypes : Derived Types

New types can be derived by using the declaration operators * : pointer & : reference [] : array

(): function

and the structure definition mechanism (eg. struct})

Page 28: The C++ Programming  Language

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;

Page 29: The C++ Programming  Language

Types : voidTypes : void

Usages : 1. Specify that a function does not return a value

2. The base type for pointers to objects of unkno

wn type void f(); // f does not return a value void* pv; // pointer to object of unknown type

Page 30: The C++ Programming  Language

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);

}

Page 31: The C++ Programming  Language

NotesNotes

A pointer of any type can be assigned to a value of type void* 1.For passing pointers to functions that are not allo

wed to make assumptions about the type of the object

2. For returning untyped objects from functions

Page 32: The C++ Programming  Language

Types : PointersTypes : Pointers

For most types T, T* is the type pointer to T

int *pi;char** cpp; // pointer to pointer to charint (*vp)[4]; // pointer to array of 4 intsint (*fp)(char,char*); // pointer to function

// taking (char, char*) arguments // and return an int

Page 33: The C++ Programming  Language

NotesNotes

pi

cpp

vp

fp

123

‘a’

function code forint f(char,char*)

123

234456678

Page 34: The C++ Programming  Language

Types : ArraysTypes : 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

Page 35: The C++ Programming  Language

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

Page 36: The C++ Programming  Language

NotesNotes

Only substraction between pointes is allowed.

-> conversion needed

void *p = &aa; void *q = p + 10;

Page 37: The C++ Programming  Language

Types : StructuresTypes : 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;

Page 38: The C++ Programming  Language

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

Page 39: The C++ Programming  Language

NotesNotes

adpad

name

number

adpad

name

number

“Jim Dandy”

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

Page 40: The C++ Programming  Language

Types : Type EqualencyTypes : 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

Page 41: The C++ Programming  Language

A declaration prefixed by the keyword “typedef” declares a new name for the type

typedef char* Pchar; Pchar p1; char* p3 = p1;

Page 42: The C++ Programming  Language

Types: ReferenceTypes: 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

Page 43: The C++ Programming  Language

NotesNotes

1 1

i j,r

‘a’

p ch r,ch

‘a’

char ch; char ch;char *p = &ch; char &r = ch;

*p = ‘a’; r = ‘a’ ;

Page 44: The C++ Programming  Language

LiteralsLiterals 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

Page 45: The C++ Programming  Language

Character constants A character constant is a character enclosed in si

ngle quotes It is possible to represent a character as a one-, two-, or three-digit octal number ( \ followed by oct

al 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'

Page 46: The C++ Programming  Language

NotesNotes 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

Page 47: The C++ Programming  Language

Named ConstantsNamed 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};

Page 48: The C++ Programming  Language

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

Page 49: The C++ Programming  Language

NotesNotes

pc

“asdf”

“ghjk”

“asdf”pc

cp

“asdf”

“asdf”

cp

fixed fixed

v.s.

Page 50: The C++ Programming  Language

Named Constants : Named Constants : const v.s #defined Macroconst 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;

Page 51: The C++ Programming  Language

const gives more type information Macro is just text substitution, but const isn't

#define NUM1 2 + 2const 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}

Page 52: The C++ Programming  Language

Named Constants : EnumeratiNamed Constants : Enumerationsons

Alternative method for naming integer constants enum { ASM, AUTO, BREAK };

Values can also be explicitly given to enumerators enum int16 { sign = 010000, most_significant = 04000, least_significant = 1 };

Page 53: The C++ Programming  Language

FieldsFields Bundling several tiny variables together in a struct 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;

};

Page 54: The C++ Programming  Language

UnionsUnions Used when members are not used simultan- eously

struct entry { char* name; char type; union { char* string_value; int int_value; };

};