epsii 59:006 spring 2004. call-by-value example #include void increment(int); //prototype for...
TRANSCRIPT
EPSII
59:006
Spring 2004
Call-by-value example#include <stdio.h>void increment(int); //prototype for increment function
int main(void) { int a=1; printf("Value of a before function call is %d\n", a); increment(a); printf("Value of a after function call is %d\n", a); return 0; }
void increment(int x) { //parameter passed by value printf("Starting value of parameter x in function is %d\n",x); x=x+1; printf("Ending value of parameter x in function is %d\n",x); }
Value of a before function call is 1Starting value of parameter x in function is 1Ending value of parameter x in function is 2Value of a after function call is 1
Note: incrementing the parameter xdoes not affect the value of the argument a
Functions – Quick Review Functions
Modularize a program All variables declared inside functions are local variables
Known only in function defined Parameters
Communicate information to/from functions Act like local variables within the function
Benefits of functions Divide and conquer
Manageable program development Software reusability
Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions)
Avoid code repetition
Function Definitions
Function definition formatreturn-value-type function-name( parameter-list ){ declarations and statements}
Function-name: any valid identifier Return-value-type: data type of the result (default int)
void – indicates that the function returns nothing Parameter-list: comma separated list, declares parameters
A type must be listed explicitly for each parameter unless the parameter is of type int (However you should explicitly specify the type, even for ints)
Function Definitions Function definition format (continued)
return-value-type function-name( parameter-list ){ declarations and statements}
Declarations and statements: function body (block) Variables can be declared inside blocks (can be nested) Functions can not be defined inside other functions
Returning control If nothing returned:
return; or, until execution reaches right brace (end of function)
If something returned: return expression;
Function prototype (3 parameters)
Input values
Call function
Function definition
Program Output
1 /* Fig. 5.4: fig05_04.c2 Finding the maximum of three integers */3 #include <stdio.h>45 int maximum( int, int, int ); /* function prototype */67 int main()8 {9 int a, b, c;1011 printf( "Enter three integers: " );12 scanf( "%d%d%d", &a, &b, &c );13 printf( "Maximum is: %d\n", maximum( a, b, c ) );1415 return 0;16 }1718 /* Function maximum definition */19 int maximum( int x, int y, int z )20 {21 int max = x;2223 if ( y > max )24 max = y;2526 if ( z > max )27 max = z;2829 return max;30 }Enter three integers: 22 85 17Maximum is: 85
Function Prototypes Function prototype declares:
Function name Parameter types – what the function takes in Return type – data type function returns (default int) Used by compiler to determine typing information
about functions. Prototype required only if function definition comes
after use in program (But it is a good idea to always use them.)
The function with the prototypeint maximum( int, int, int );
Takes in 3 ints Returns an int
Header Files Header files
Contain function prototypes for library functions <stdlib.h> , <math.h> , etc Load with #include <filename>
#include <math.h> Custom header files:
You can create your own header files---e.g. containing prototypes, function definitions, etc
Save as filename.h Load into other files with #include "filename.h" The quotes around the file name tell the C
preprocessor to look for the named file in the current working directory
Calling Functions: Call by Value and Call by Reference
Used when invoking functions Call by value
Argument’s current value is passed to function Changes to the parameter in the function do not affect the value
of the argument Use when function does not need to modify argument
Avoids accidental changes Call by reference
Passes the address (location) of the argument to the function Changes to the parameter in function modify the argument Only used with trusted functions
For now, we focus on call by value
Random Number Generation rand function
#include <stdlib.h> Returns "random" number between 0 and RAND_MAX (at least 32767)
i = rand(); Pseudorandom
Preset sequence of "random" numbers Same sequence for every function call
Scaling To get a random number between 1 and n
1 + ( rand() % n ) rand() % n returns a number between 0 and n - 1 Add 1 to make random number between 1 and n
1 + ( rand() % 6) number between 1 and 6
Random Number Generation
srand function <stdlib.h> Takes an integer “seed” to initialize the "random" sequence
srand( seed ); srand( time( NULL ) ); //need #include <time.h>
time( NULL ) Returns the current time (in seconds) since some starting
time which is system-dependent For Unix this starting time is 00:00:00 GMT Jan 1, 1970
(the ‘Epoch’ – the birth of Unix)
Used this way, time() “randomizes" the seed
Initialize seed
Input value for seed
Use srand to change random sequence
Define Loop
Generate and output random numbers
1 /* Fig. 5.9: fig05_09.c
2 Randomizing die-rolling program */
3 #include <stdlib.h>
4 #include <stdio.h>
5
6 int main()
7 {
8 int i;
9 unsigned seed;
10
11 printf( "Enter seed: " );
12 scanf( "%u", &seed );
13 srand( seed );
14
15 for ( i = 1; i <= 10; i++ ) {
16 printf( "%10d", 1 + ( rand() % 6 ) );
17
18 if ( i % 5 == 0 )
19 printf( "\n" );
20 }
21
22 return 0;
23 }
This exampleshows that a givenseed alwaysgenerates thesame randomnumber sequence
Program Output
Enter seed: 867 2 4 6 1 6 1 1 3 6 2
Enter seed: 67 6 1 4 6 2 1 6 1 6 4
Enter seed: 67 6 1 4 6 2 1 6 1 6 4
Example of time() functionint main(void) { int i; int secs_per_year=31536000; i = time(NULL); printf("The current time returned by time() is %d\n", i); printf("This represents the year %d\n", 1970 + (i/secs_per_year)); }
Note that time()returns a different valueeach time the programruns
l-ecn003% gcc timeTest.c l-ecn003% a.outThe current time returned by time() is 1076704538This represents the year 2004l-ecn003% a.outThe current time returned by time() is 1076704544This represents the year 2004
Example: A Game of Chance
Craps simulator Rules
Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 - value becomes player's "point"
Player must roll his/her point again before rolling 7 to win
rollDice prototype
Initialize variables
Seed srand
Define switch statement for win/loss/continue
Loop
1 /* Fig. 5.10: fig05_10.c2 Craps */3 #include <stdio.h>4 #include <stdlib.h>5 #include <time.h>67 int rollDice( void );89 int main()10 {11 int gameStatus, sum, myPoint;1213 srand( time( NULL ) );14 sum = rollDice(); /* first roll of the dice */1516 switch ( sum ) {17 case 7: case 11: /* win on first roll */18 gameStatus = 1;19 break;20 case 2: case 3: case 12: /* lose on first roll */21 gameStatus = 2;22 break;23 default: /* remember point */24 gameStatus = 0;25 myPoint = sum;26 printf( "Point is %d\n", myPoint );27 break;28 }2930 while ( gameStatus == 0 ) { /* keep rolling */31 sum = rollDice();32
Print win/loss
Program Output
33 if ( sum == myPoint ) /* win by making point */
34 gameStatus = 1;
35 else
36 if ( sum == 7 ) /* lose by rolling 7 */
37 gameStatus = 2;
38 }
39
40 if ( gameStatus == 1 )
41 printf( "Player wins\n" );
42 else
43 printf( "Player loses\n" );
44
45 return 0;
46 }
47
48 int rollDice( void )
49 {
50 int die1, die2, workSum;
51
52 die1 = 1 + ( rand() % 6 );
53 die2 = 1 + ( rand() % 6 );
54 workSum = die1 + die2;
55 printf( "Player rolled %d + %d = %d\n", die1, die2, workSum );
56 return workSum;
57 }
Player rolled 6 + 5 = 11Player wins
Program Output
Player rolled 6 + 6 = 12Player loses
Player rolled 4 + 6 = 10Point is 10Player rolled 2 + 4 = 6Player rolled 6 + 5 = 11Player rolled 3 + 3 = 6Player rolled 6 + 4 = 10Player wins
Player rolled 1 + 3 = 4Point is 4Player rolled 1 + 4 = 5Player rolled 5 + 4 = 9Player rolled 4 + 6 = 10Player rolled 6 + 3 = 9Player rolled 1 + 2 = 3Player rolled 5 + 2 = 7Player loses
Storage Classes Storage class specifiers
Storage duration – how long a variable retains its value in memory
Scope – where a variable can be referenced in a program
Linkage – specifies the files in which an identifier (variable or function name) is known (more in Chapter 14)
C Storage Classes
auto (automatic) register static extern (external)
Automatic Storage Class Automatic storage
Variable created and destroyed within its block If an initializer is used, the variable is reinitialized each time its
block is entered.
Default for local variables of functions
auto double x, y; register: tries to put variable into high-speed registers
(not of much significance for modern compilers and computers)
Can only be used for automatic variables
register int counter = 1;
Static Storage Class Static storage
Variables exist for entire program executionDefault initial value of zeroCan specify an alternative initial value:
static int x = 1; Static variables are initialized once, at beginning of
program execution.Static local variables defined in functions:
Keep value after function ends Only known in their own function
Static Variable Example#include <stdio.h>int counter(void); //prototype
int main(void) { int value; value = counter(); printf("value = %d\n", value); value = counter(); printf("value = %d\n", value); value = counter(); printf("value = %d\n", value); return 0; }
int counter() { static int count=0; //would be initialized by default count = count +1; return count; }
value = 1value = 2value = 3
Try this example without thestatic designation and seewhat happens.
Extern Storage classextern: default for global variables and
functions declared outside of the scope of any function. Known in all functions global (extern) variable declarations should be
avoided unless absolutely necessary
Scope Rules File scope
Identifier defined outside of function body known in all functions defined in the file applies to:
global variables (variables defined outside of any function definition
function names function prototypes
Function scope Can only be referenced inside a function body Used only for labels (start:, case: , etc.) This is a language detail that you don’t need to worry
about.
Scope Rules Block scope
Identifier declared inside a block {…} Block scope begins at declaration, ends at right
brace Used for:
local variables function parameters
Can actually define local variables in any C block (not recommended)
Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block
Function prototype scope Used for identifiers in parameter list
Function prototypes
Initialize global variable
Initialize local variable
Initialize local variable in block
Call functions
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 */
Output Results
Function definitions
31
32 printf( "local x in main is %d\n", x );
33 return 0;
34 }
35
36 void a( void )
37 {
38 int x = 25; /* initialized each time a is called */
39
40 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 }
44
45 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 }
53
54 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 }
Program Output
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
Scope Rules—Style Guidelines for this Class Do not use extern (global) variables unless there is an
absolutely compelling reason. If you think there is a compelling reason, you are probably wrong global variables can introduce subtle errors into programs
Declare local (block scope) variables only at the beginning of functions (including main() ) Don’t declare local variables inside the body of loops or other
control structures Don’t use the register designation
it’s probably meaningless anyway Declare variables as static only when they need to
retain their value between invocations of a function.