Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer...

11
Dale Robert CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Dale Roberts, Lecturer IUPUI IUPUI [email protected] [email protected]

Transcript of Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer...

Page 1: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

CSCI 230

Functions Scope, Parameter Passing,

Storage Specifiers

Department of Computer and Information Science,School of Science, IUPUI

Dale Roberts, LecturerDale Roberts, Lecturer

IUPUIIUPUI

[email protected]@cs.iupui.edu

Page 2: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

1 /* Fig. 5.12: fig05_12.c2 A scoping example */3 #include <stdio.h>45 void a( void ); /* function prototype */6 void b( void ); /* function prototype */7 void c( void ); /* function prototype */89 int x = 1; /* global variable */1011 int main()12 {13 int x = 5; /* local variable to main */1415 printf("local x in outer scope of main is %d\n", x );1617 { /* start new scope */18 int x = 7;1920 printf( "local x in inner scope of main is %d\n", x );21 } /* end new scope */2223 printf( "local x in outer scope of main is %d\n", x );2425 a(); /* a has automatic local x */26 b(); /* b has static local x */27 c(); /* c uses global x */28 a(); /* a reinitializes automatic local x */29 b(); /* static local x retains its previous value */30 c(); /* global x also retains its value */

1. Function prototypes

2. Initialize global variable

3. Initialize local variable

4. Initialize local variable in block

5. Call functions

6. Output results

Page 3: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

3132 printf( "local x in main is %d\n", x );33 return 0;34 }3536 void a( void )37 {38 int x = 25; /* initialized each time a is called */3940 printf( "\nlocal x in a is %d after entering a\n", x );41 ++x;42 printf( "local x in a is %d before exiting a\n", x );43 }4445 void b( void )46 {47 static int x = 50; /* static initialization only */48 /* first time b is called */49 printf( "\nlocal static x is %d on entering b\n", x );50 ++x;51 printf( "local static x is %d on exiting b\n", x );52 }5354 void c( void )55 {56 printf( "\nglobal x is %d on entering c\n", x );57 x *= 10;58 printf( "global x is %d on exiting c\n", x );59 }

local x in outer scope of main is 5local x in inner scope of main is 7local x in outer scope of main is 5 local x in a is 25 after entering alocal x in a is 26 before exiting a local static x is 50 on entering blocal static x is 51 on exiting b global x is 1 on entering cglobal x is 10 on exiting c local x in a is 25 after entering alocal x in a is 26 before exiting a local static x is 51 on entering blocal static x is 52 on exiting b global x is 10 on entering cglobal x is 100 on exiting clocal x in main is 5

Program Output

Page 4: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Scope RulesScope Rules

File scope File scope Identifier defined outside function, known in all functionsIdentifier defined outside function, known in all functions

Used for global variables, function definitions, function prototypesUsed for global variables, function definitions, function prototypes

Function scope Function scope Can only be referenced inside a function bodyCan only be referenced inside a function body

Used only for labels (Used only for labels (start:start:, , case:case: , etc.) , etc.)

Block scope Block scope Identifier declared inside a block Identifier declared inside a block

Block scope begins at declaration, ends at right braceBlock scope begins at declaration, ends at right brace

Used for variables, function parameters (local variables of function)Used for variables, function parameters (local variables of function)

Outer blocks "hidden" from inner blocks if there is a variable with Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner blockthe same name in the inner block

Function prototype scope Function prototype scope Used for identifiers in parameter listUsed for identifiers in parameter list

Page 5: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Header FilesHeader Files

Header filesHeader filesContain function prototypes for library functionsContain function prototypes for library functions

<stdlib.h><stdlib.h> , , <math.h><math.h> , etc , etc

Load with Load with #include <filename>#include <filename>#include <math.h>#include <math.h>

Custom header filesCustom header filesCreate file with functions Create file with functions

Save as Save as filename.hfilename.h

Load in other files with Load in other files with #include "filename.h"#include "filename.h"

Reuse functionsReuse functions

Page 6: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Calling Functions: Call by Value and Call by ReferenceCalling Functions: Call by Value and Call by Reference

Used when invoking functionsUsed when invoking functionsCall by valueCall by value

Copy of argument passed to functionCopy of argument passed to functionChanges in function do not effect originalChanges in function do not effect originalUse when function does not need to modify argumentUse when function does not need to modify argument

Avoids accidental changesAvoids accidental changesExampleExample::addone(int);addone(int);main ()main ()

{{int i = 5, j;int i = 5, j;j=addone(i);j=addone(i);printf(“%d %d\n”,i, j);printf(“%d %d\n”,i, j); 5 65 6

}}

addone(int x)addone(int x){{return ++x;return ++x;

}}

Page 7: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Call by reference (Passing Address)Call by reference (Passing Address)This is not actually call by reference, although some books called This is not actually call by reference, although some books called this ‘call-by-reference’this ‘call-by-reference’Passes original argumentPasses original argumentChanges in function effect original using Changes in function effect original using && operator to pass operator to pass addressaddressOnly used with trusted functionsOnly used with trusted functions

ExampleExample::addone(int *);addone(int *);main ()main ()

{{int i = 5, j;int i = 5, j;j=addone(&i);j=addone(&i);printf(“%d %d\n”,i, j);printf(“%d %d\n”,i, j); 6 6

66}}

addone(int *x)addone(int *x){{return ++(*x);return ++(*x);

}}

For now, we focus on call by valueFor now, we focus on call by value

Calling Functions: Call by Value and Call by ReferenceCalling Functions: Call by Value and Call by Reference

Page 8: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Storage ClassesStorage Classes

Storage class specifiersStorage class specifiersStorage duration Storage duration –– how long an object exists in memory how long an object exists in memory

Scope Scope –– where object can be referenced in program where object can be referenced in program

Linkage Linkage –– specifies the files in which an identifier is known (more in specifies the files in which an identifier is known (more in Chapter 14)Chapter 14)

Automatic storageAutomatic storageObject created and destroyed within its blockObject created and destroyed within its block

autoauto: default for local variables and usually stored in : default for local variables and usually stored in StackStack..auto double x, y;auto double x, y;

registerregister: tries to put variable into high-speed registers: tries to put variable into high-speed registersCan only be used for automatic variablesCan only be used for automatic variablesregister int counter = 1;register int counter = 1;

ExampleExample:: f(register int c,n)f(register int c,n)

{{

register int i;register int i;

……

}}

Page 9: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Storage ClassesStorage Classes

Static storage Static storage Variables exist for entire program executionVariables exist for entire program execution

Default value of zeroDefault value of zero

staticstatic: local variables defined in functions. : local variables defined in functions. Keep value after function endsKeep value after function ends

Only known in their own function (does not change scope) Only known in their own function (does not change scope) ExampleExample::

get_char()get_char()

{{

static char buf[128];static char buf[128];

static int bufp=0;static int bufp=0;

}}

Page 10: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

Storage ClassesStorage ClassesIf an external variable is to be referred to before it is defined, or if it is defined If an external variable is to be referred to before it is defined, or if it is defined in a different source file from the one where it is being used, thenin a different source file from the one where it is being used, then extern extern declaration is necessarydeclaration is necessaryexternextern: default for global variables and functions: default for global variables and functions

Known in any functionKnown in any functionUsage: if large number of variables must be shared among functions, external Usage: if large number of variables must be shared among functions, external variables are more convenient and efficient than long argument listvariables are more convenient and efficient than long argument list

ExampleExample::In file 1:In file 1: ……

int sp=0;int sp=0;double val[12];double val[12];……

In file 2;In file 2;extern int sp;extern int sp;extern double val[];extern double val[];int push(f)int push(f)double f;double f;{{

……}}……

Page 11: Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.

Dale Roberts

AcknowledgementsAcknowledgements