UMBC CS 201, Spring 02
UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | lectures | news | help

Function prototypes are essential

What happens when a function prototype is missing?

The Program That Doesn't Compile

/********************************************* ** File: proto.c ** Author: S. Bogar ** Date: 8/3/99 ** Section: 101 ** SSN: 123-45-6789 ** EMail: bogar@cs.umbc.edu ** ** Demonstrate the need for prototypes ** This is the buggy version. *********************************************/ #include <stdio.h> /* No prototypes in this version */ int main() { double x; int n, m; x = Add3 (5.0); printf("x = %f\n", x); n = Add3 (10.0); printf("n = %d\n", n); m = (int) Add3 (17.0); printf("m = %d\n", m); return 0; } /********************************************* ** Function: Add3 ** Usage: x = Add3 (y); ** ** Input: an arbitrary double to which 3.0 is added ** Output: returns y + 3.0 *********************************************/ double Add3 (double y) { double z; z = y + 3.0; return (z); }

When trying to compile

linux3[106] % gcc -Wall -ansi proto.c proto.c: In function `main': proto.c:22: warning: implicit declaration of function `Add3' proto.c: At top level: proto.c:43: warning: type mismatch with previous implicit declaration proto.c:22: warning: previous implicit declaration of `Add3' proto.c:43: warning: `Add3' was previously implicitly declared to return `int' linux3[107] % a.out x = 716910456.000000 n = 21 m = 7 linux3[108] %

The Fixed Program

/******************************************** ** File: proto2.c ** Author: S. Bogar ** Date: 8/3/99 ** Section: 101 ** SSN: 123-45-6789 ** EMail: bogar@cs.umbc.edu ** ** Demonstrate the need for prototypes ** This is the corrected version. *********************************************/ #include <stdio.h> /* Include the prototype in this version */ double Add3(double); int main () { double x; int n, m; x = Add3 (5.0); printf ("x = %f\n", x); n = Add3 (10.0); printf ("n = %d\n", n); m = (int) Add3 (17.0); printf ("m = %d\n", m); return 0; } /********************************************* ** Function: Add3 ** Usage: x = Add3 (y); ** ** Input: an arbitrary double, y, to which 3.0 is added ** Output: returns y + 3.0 *********************************************/ double Add3 (double y) { double z; z = y + 3.0; return (z); }

The Sample Run

x = 8.000000 n = 13 m = 20

The Lesson


CSEE | 201 | 201 S'02 | lectures | news | help

Last Modified - Thursday, 17-Jan-2002 13:51:57 EST