Computers in Engineering - 308-208 Lecture 18
Computers in Engineering - 308-208


Lesson 18 - Learning Goals



18.1 Learn the Scope of C variables and procedures

18.2 Learn about Function Prototypes and how to use them



''SCOPE'' OF C VARIABLES AND PROCEDURES

LONGEVITY OF C VARIABLES


FUNCTIONS

IN FORTRAN :

! THIS PROGRAM COMPUTES THE CUBE OF ITS INPUT.
REAL FUNCTION CUBE(X)
   IMPLICIT NONE
   REAL :: X
   CUBE = X * X * X
END FUNCTION CUBE

IN C :

/* This program computes the cube of its input */
real cube (x)
float x;
{
   return (x * x * x);
}

SIMILARITIES :

DIFFERENCES :


STATIC VS. AUTOMATIC VARIABLES

STATIC :

AUTOMATIC :

EXAMPLE

#include <stdio.h>

void ephemeral ( ), permanent ( );

main()
{
   ephemeral ( );
   permanent ( );
   ephemeral ( ); /* New value */
   permanent ( ); /* Keep old value */
   printf ("\n");
}

void ephemeral ( ) 
{
   int value = 0;
   printf ("E: %d\t", value++);
}

void permanent ( ) 
{
   static int value = 0;
   printf ("P: %d\t", value++);
}

~~~~~~~~~~~~~~~~~~~~~~

Output :

E: 0 P: 0 E: 0 P: 1 


PROTOTYPE DECLARATION

PROTOTYPE EXAMPLE

#include <stdio.h>

/* Two Prototype Declarations */

float average (float, float);
void swap (float *, float *); 
        /* Both arguments to swap are  */
        /* pointers to floats.         */

main () {
   float a, b, ave;
   a = 3.396;
   b = 5.2;
   ave = average (a,b);
   swap (&a,&b);
   printf ("The average of %.2f and %.2f is %.2f\n",
      a, b, ave); /* Print 2 sig. figures */
}

float average (float x, float y) {
   return (x+y)/2;
}

void swap (float *x, float *y) {
   float temp;
   temp = *x;
   *x = *y;
   *y = temp;
}

~~~~~~~~~~~~~~~~~~~~~~

OUTPUT :

The average of 5.20 and 3.40 is 4.30


PASSING ARRAYS IN C

PASSING ARRAYS - EXAMPLES

IN FORTRAN :

PROGRAM ARRAYS
   IMPLICIT NONE
   INTEGER :: A(50), TOP, BIGEST
   ...
   TOP = BIGEST (A, 50)
   ...
   ! RETURN LARGEST OF FIRST N INTS OF B
   INTEGER FUNCTION BIGEST (B, N)
      INTEGER B(*)
      BIGEST = -9999
      DO 10 I=1,N
10       IF (B(I).GT.BIGEST) BIGEST = B(I)
   STOP
END PROGRAM ARRAYS

IN C :

main ( )
{ 
   int a[50], top ;
   ...
   top = bigest (a, 50) ;
   ...
}
/* Return largest of first n ints of b */
int bigest (int b[ ], int n) 
{
   int i, largest;
   for ( i=0 , largest=-9999 ; i<n ; i+=1)
      if (b[i] > largest) largest=b[i];
   return (largest);
}


On to the next lecture
Go back to lecture menu

Copyright © 1996 McGill University. All rights reserved.