1 review of class on oct. 28. 2 outline pointer pointers to void call-by-reference basic scope...

66
1 Review of Class on Oct. 28

Post on 19-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

1

Review of Class on Oct. 28

2

Outline

PointerPointers to voidCall-by-ReferenceBasic Scope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

3

Pointer

Pointers: Pointer variables can be declared in

programs and then used to take addresses as valuesDeclaration

o double *pb, x;Assignment

o pb = &x;Dereferencing

o Access the value of the variable to which the pointer points by dereference operator *:

*pb = 3; What is the value of x?

*pointer

pointer = address;

DataType *pointer1, *pointer2;

4

Pointer

Pointers: What is the legal range of values of any

pointer?a set of positive integers that are interpreted as

machine addresses on a particular C system, andthe special address NULL, 0

o stdio.h: #define NULL 0o NULL can be used to represent false

while(NULL) printf(“loop\n”);

5

Pointer#include <stdio.h>int main(void){ int a =1,b =2; int *pa, *pb; pa = &a; pb = &b; printf("value of b: %d \n", *pb); *pb=3; printf("Input an integer: "); scanf("%d", pa);}

Declaration of a pointer: DataType *pointer; Assign address to a pointer: pointer = address;Access the value of the variable to which the pointer points: *pointer

6

Outline

PointerPointers to voidCall-by-ReferenceBasic Scope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

7

Call-by-Reference

Call-by-value Function Invocation

fun_name(exp1, exp2); All arguments are passed call-by-value

Each argument is evaluated, and its value is used locally in place of the corresponding formal parameter.

If a variable is passed to a function, the stored value of that variable in the calling environment is not changed.

8

Call-by-Reference#include <stdio.h>void swap(int, int);int main(void){ int a=3, b=7; swap(a,b); printf("main: %d %d\n", a, b); return 0;}void swap(int sa, int sb){ int tmp; tmp = sa; sa = sb; sb = tmp; printf("swap: %d %d\n", sa, sb);}

% a.outswap: 7 3main: 3 7

Memory

a

b 7

3

swap: sa

swap: sb

swap: tmp

7

3

3

7

3

9

Call-by-Reference#include <stdio.h>void swap(int* , int* );int main(void){ int a=3, b=7; printf("Addr %u, %u\n", &a,&b); swap(&a,&b); printf("main: %d %d\n", a, b); return 0;}void swap(int *pa, int *pb){ int tmp; tmp = *pa; *pa = *pb; *pb = tmp; printf("swap: %d %d\n", *pa, *pb);}

% a.outAddr 4290705268, 4290705264swap: 7 3main: 7 3

Memory

a

b 7

3

swap: pa

swap: pb

swap: tmp 3

4290705268

4290705264

4290705268

4290705264

7

3

10

Call-by-Reference#include <stdio.h>void swap(int* , int* );int main(void){ int a=3, b=7; printf("Addr %u, %u\n", &a,&b); swap(&a,&b); printf("main: %d %d\n", a, b); return 0;}void swap(int *a, int *b){ int tmp; tmp = *a; *a = *b; *b = tmp; printf("swap: %d %d\n", *a, *b);}

How to modify the values of the variables referred to in the argument list?

Declaring a function parameter to be a pointerUsing the pointer in the function bodyPassing an address as an argument when the function is called

11

End of Review

12

Class on Nov 2

13

Outline

PointerPointers to voidCall-by-ReferenceBasic Scope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

14

Pointers to void

In ANSI C, one pointer can be assigned to another only when

they both have the same type, or when one of them is of type pointer to void

void * can be considered as a generic pointer type NULL can be assigned to any pointer.

Example:int *p;double *q;void *v;p = 0;p = NULL;p = (int *) 1;p = v = (int *) q;p = q;p =1;

/* legal *//* legal *//* legal *//* legal *//* illegal *//* illegal */

15

Outline

PointerPointers to voidCall-by-ReferenceBasic Scope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

16

Given a variable, Date type

set aside an appropriate amount of memory

instruct the machine to perform specified operations correctly.

Where can we use this variable in the code? The scope of the variable

During the program execution, when is the memory allocated to the variable and when is the memory released?The lifetime of the variableStorage Class

17

Outline

PointerPointers to voidCall-by-ReferenceBasic Scope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

18

Scope Rulesinclude <stdio.h>int f(int n);

int main(void){ int i; for (i=1; i<=8; i++) printf("sum of 1 to %d = %d\n",i, f(i));}/* calculate 1+2+3+…..+n */int f(int n){ int i , sum=0; for (i=0; i<=n; i++) sum += i; return sum;}

Example

print out the results of the following expressions:11+21+2+3 1+2+3+41+2+3+4+51+2+3+4+5+61+2+3+4+5+6+71+2+3+4+5+6+7+8

Can we have two variables with the same name i?the scope of an

identifier

19

Scope Rules

What is the scope of an identifier? The part of the code in which the identifier

is accessible.include <stdio.h>int f(int n);int main(void){ int i; for (i=1; i<=8; i++) printf("sum of 1 to %d = %d\n",i, f(i));}int f(int n){ int i , sum=0; for (i=0; i<=n; i++) sum += i; return sum;}

20

Scope Rules

How to decide the scope of a given identifier? This concept depends on the notion of a

block, which is a compound statement with declarations.

21

Scope Rules

include <stdio.h>int f(int n);

int main(void){ int i; for (i=1; i<=8; i++) printf("sum of 1 to %d = %d\n",i, f(i));}

int f(int n){ int i , sum=0; for (i=0; i<=n; i++) sum += i; return sum;}

The body of function definition can be considered as a block.

22

Scope Rules

How to decide the scope of a given identifier? This concept depends on the notion of a

block, which is a compound statement with declarations.

Identifiers are accessible only within the block in which they are declared.

They are unknown outside the boundaries of that block.

23

Scope Rules

include <stdio.h>int f(int n);

int main(void){ int i; for (i=1; i<=8; i++) printf("sum of 1 to %d = %d\n",i, f(i));}

int f(int n){ int i , sum=0; for (i=0; i<=n; i++) sum += i; return sum;}

The i declared in function main is unknown only one variable with name i is accessible

The i declared in function f is unknown only one variable with name i is accessible

Variables are unknown outside the block in which they are declared.

24

Scope Rules

#include <stdio.h>int main(void){ { int b =1; printf("%d\n", b); } printf("%d\n", b); return 0;}

Identifiers are accessible only within the block in which they are declared.

% gcc scope3.cscope3.c: In function `main':scope3.c:7: error: `b' undeclared (first use in this function)scope3.c:7: error: (Each undeclared identifier is reported only oncescope3.c:7: error: for each function it appears in.)

25

Scope Rules

#include <stdio.h>int main(void){ int a = 2; int *p = &a; printf("%d\n", a); { int a= 7; printf("%d\n", a); printf("%d\n", *p); } printf("%d\n", ++a); return 0;}

% a.out2723

the inner block a hides the outer block a

What if same identifier used in different declarations?

26

Scope Rulesinclude <stdio.h>int f(int n);

int main(void){ int i; float i; for (i=1; i<=8; i++) printf("sum of 1 to %d = %d\n",i, f(i));}

int f(int n){ int i , sum=0; for (i=0; i<=n; i++) sum += i; return sum;}

We cannot declare two variables with the same name in the same block.

% gcc scope0.cscope0.c: In function `main':scope0.c:5: error: conflicting types for `i'scope0.c:4: error: previous declaration of `i'%

27

Scope Rules

Summary The scope of an identifier

The part of the code in which the identifier is accessible.

This concept depends on the notion of a block, which is a compound statement with declarations.

The basic rule of scoping Identifiers are accessible only within the block in

which they are declared.They are unknown outside the boundaries of that

block. It is not allowed to declare more than one variable

with the same name within a block.

28

Outline

PointerPointers to voidCall-by-ReferenceBasic Scope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

29

Given a variable, Date type

Set aside an appropriate amount of memory

Performance correct instructions for operations on the variable

Where can we use this variable in the code? The scope of the variable

During the program execution, when is the memory allocated to the variable and when is the memory released?The lifetime of the variable

Storage Class

30

Storage Classes

What is an identifier’s storage class? An important attribute of an identifier,

scope of the code where it is accessibletime span that it exists in memory during

program execution Storage Classes:

automatic, external, register, static, and static external

o Declarationo scopeo Life span

31

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

Outline

AutomaticExternalRegisterStaticStatic external

32

Storage Classes — auto

How to declare an automatic variable? Block: A compound statement with

declarations By default, variables declared within blocks

are of storage class automatic. The keyword auto can be used to explicitly

specify the storage class

33

include <stdio.h>int f(int n);

int main(void){ int i; for (i=1; i<=8; i++) printf("sum of 1 to %d = %d\n",i, f(i));}

int f(int n){ int i , sum=0; for (i=0; i<=n; i++) sum += i; return sum;}

Storage Classes — auto

34

Storage Classes — auto

Scope: The block in which it is declared

Time span: When a block is entered, the system allocates

memory for the automatic variables. Within that block, these variables are defined and

are considered local to the block When the block is exited, the system releases the

memory that was set aside for the automatic variables.The values of these variables are lost

If the block is reentered, the system once again allocates memory, but previous values are lost.

35

Storage ClassesStorag

e Classe

s

Declaration

Scope Life span

Auto within a block

block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Extern Outside a function

All the functions declared after it

The whole execution (Storage is permanently

assigned)

Register

(register) within a

block

Block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Static (static)within a

block

Block in which it is declared

The whole execution (Storage is permanently

assigned)

Static extern

(static)Outside a function

The remainder of the file in which it is

declared

The whole execution (Storage is permanently

assigned)

36

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

Outline

AutoExternalRegisterStaticStatic external

37

Storage Classes — extern

extern variable a variable’s storage class is extern if it is

declared outside a function Keyword extern

int a=1, b=2, c=3; is equivalent to extern int a=1, b=2, c=3;

#include <stdio.h>int a=1, b=2, c=3;int f(void);int main(void){ a = b = c = 4; printf("%3d\n", f()); return 0;}int f(void){ return (a+b+c);}

38

Storage Classes — extern

Scope: Global to all functions declared after it.

life span of extern variable Storage is permanently assigned to it Upon exit from the block or function, the

external variables retain their values.

Why external variables? They can be used to transmit values across

functions

39

Storage Classes — extern

#include <stdio.h>int a=1, b=2, c=3;int f(void);int main(void){ printf("%3d\n", f()); printf("%3d%3d%3d\n", a, b, c); return 0;}int f(void){ a = b = c = 4; return (a+b+c);}

% a.out 12 4 4 4

The external variables retain their values across block and function exit.

40

Storage Classes — extern

#include <stdio.h>int a=1, b=2, c=3;int f(void);int main(void){ printf("%3d\n", f()); printf("%3d%3d%3d\n", a, b, c); return 0;}int f(void){ int b, c; a = b = c = 4; return (a+b+c);}

% a.out 12 4 2 3

They may be hidden if the identifier is redefined

41

Storage Classes — extern

external variables in large program The ability to compile files separately is

important when writing large program. Question:

When a file is compiled, how can the compiler gets the information of the external variables declared in other file?

42

Storage Classes — extern

#include <stdio.h>int a=1, b=2, c=3;int f(void);int main(void){ printf("%3d\n", f()); printf("%3d%3d%3d\n", a, b, c); return 0;}

file1.c int f(void){ int b, c; a = b = c = 4; return (a+b+c);}

file2.c

When file2.c is compiled separately, how can the compiler gets the information of external variable a?

43

Storage Classes — extern

#include <stdio.h>int a=1, b=2, c=3;int f(void);int main(void){ printf("%3d\n", f()); printf("%3d%3d%3d\n", a, b, c); return 0;}

file1.c int f(void){ int b, c; a = b = c = 4; return (a+b+c);}

file2.c

% gcc file1.c file2.cfile2.c: In function `f':file2.c:3: error: `a' undeclared (first use in this function)file2.c:3: error: (Each undeclared identifier is reported only oncefile2.c:3: error: for each function it appears in.)

44

Storage Classes — extern

#include <stdio.h>int a=1, b=2, c=3;int f(void);int main(void){ printf("%3d\n", f()); printf("%3d%3d%3d\n", a, b, c); return 0;}

file1.c int f(void){ extern int a; int b, c; a = b = c = 4; return (a+b+c);}

file2.c

The use of extern in file2.c tells the compiler that the variable a is defined elsewhere

45

Storage ClassesStorag

e Classe

s

Declaration

Scope Life span

Auto within a block

block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Extern Outside a function

All the functions declared after it

The whole execution (Storage is permanently

assigned)

Register

(register) within a

block

Block in whichit is declared

Memory is allocated when the block is entered and released when the block is exited

Static (static)within a

block

Block in which it is declared

The whole execution (Storage is permanently

assigned)

Static extern

(static)Outside a function

The remainder of the file in which it is

declared

The whole execution (Storage is permanently

assigned)

46

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

Outline

AutoExternRegisterStaticStatic external

47

Storage Classes — register

How to declare register variables? register int i;

Scope and life Span, Same as automatic variables

48

Storage Classes — register

Features of register variables Tells the compiler that the variables should

be stored in high-speed memory registers, if possible.

Because resource limitations sometimes make this impossible, this storage class defaults to automatic whenever the compiler cannot allocate a register.

PurposeImprove execution speed

49

Storage ClassesStorag

e Classe

s

Declaration

Scope Life span

Auto within a block

Block in whichit is declared

Memory is allocated when the block is entered and released when the block is exited

Extern Outside a function

All the functions declared after it

The whole execution (Storage is permanently

assigned)

Register

(register) within a

block

Block in whichit is declared

Memory is allocated when the block is entered and released when the block is exited

Static (static)within a

block

Block in which it is declared

The whole execution (Storage is permanently

assigned)

Static extern

(static)Outside a function

The remainder of the file in which it is

declared

The whole execution (Storage is permanently

assigned)

50

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

Outline

AutoExternRegisterStaticStatic external

51

Storage Classes — static

static declarations static int count;

Scope: private to the block in which they are

declared

Life Span: the whole time the program is executing Allow a local variable to retain its previous

values when the block is reentered.Contrast to automatic variables, which lose

their value upon block exit.

52

#include <stdio.h>int is_prime(int n){ int k, limit; if (n==2) return 1; if (n%2==0) return 0; limit = n/2; for (k=3; k<=limit; k+=2) if (n%k==0) return 0; return 1;}int increment_count(void){ static int count = 0; return (++count);}int main(void){ int i=0; printf("Primes less than 30:\n"); for(i=2; i<=30; i++) if (is_prime(i)) printf("prime %3d: %4d\n",increment_count(),i);}

% a.outPrimes less than 30:prime 1: 2prime 2: 3prime 3: 5prime 4: 7prime 5: 11prime 6: 13prime 7: 17prime 8: 19prime 9: 23prime 10: 29

a static variable retains its previous values when the block is reentered.

53

Storage ClassesStorag

e Classe

s

Declaration

Scope Life span

Auto within a block

Block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Extern Outside a function

All the functions declared after it

The whole execution (Storage is permanently

assigned)

Register

(register) within a

block

Block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Static (static)within a

block

Block in which it is declared

The whole execution (Storage is permanently

assigned)

Static extern

(static)Outside a function

The remainder of the file in which it is

declared

The whole execution (Storage is permanently

assigned)

54

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

Outline

AutoExternRegisterStaticStatic external

55

#include “count.h”

static int count = 0;int increment_count(void){ return (++count);}

int get_count(void){ return count;}

#include <stdio.h>#include "count.h"int is_prime(int n){ ……}

int main(void){ int i=0; for(i=2; get_count()<3000; i++) { if (is_prime(i)) increment_count(); if( i%1000 ==0 || get_count()==3000) printf("%8d %8d\n", i, get_count()); }}

se.c

count.c

Variable count in file count.caccessible by

increment_count() get_count()

Unknown outside of file count.c --- private to count.c

int get_count(void);int increment_count(void);

count.h

gcc se.c count.c

%a.out 1000 168 2000 303 …… 26000 2860 27000 2961 27449 3000

Use functions provided in count.c to keep track of the number of primes less than or equal to i.

56

Storage Classes — static external

How to declare static external variables? keyword: static, declared outside a function Example

static int count = 0;int increment_count(void){ return (++count);}int get_count(void){ return count;}

57

Storage Classes — static external

Scope the remainder of the source file in which

they are declared

Life Span Storage is permanently assigned. values are retained

#include “count.h”

static int count = 0;int increment_count(void){ return (++count);}

int get_count(void){ return count;}

58

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

AutoExternalRegisterStaticStatic external

Outline

59

Storage ClassesStorag

e Classe

s

Declaration

Scope Life span

Auto within a block

Block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Extern Outside a function

All the functions declared after it

The whole execution (Storage is permanently

assigned)

Register

(register) within a

block

Block in which it is declared

Memory is allocated when the block is entered and released when the block is exited

Static (static)within a

block

Block in which it is declared

The whole execution (Storage is permanently

assigned)

Static extern

(static)Outside a function

The remainder of the file in which it is

declared

The whole execution (Storage is permanently

assigned)

60

Outline

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

61

Default Initialization

Default Initialization Both external variables and static variables

that are not explicitly initialized by the programmer are initialized to zero by the system.

62

Default Initialization

Default Initialization Automatic and register variables usually are

not initialized by the systemStart with garbage values.Although some C systems do initialize

automatic variables to zero, this feature should not be relied on.

63

Default Initialization

#include <stdio.h>int i;void f(){ static int a; printf("%d\n", a);}int main(void){ int b; printf("%d\n", b); printf("%d\n", i); f();}

% a.out-426190000

64

Outline

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

65

Outline

PointerPointers to voidCall-by-ReferenceScope RulesStorage ClassesDefault InitializationFunction Declarations and DefinitionsThe Type Qualifiers const and volatile

66

End of Chapter 8 Read 8.1 – 8.14