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

Function prototypes are essential

What happens when a function prototype is missing?

The Buggy Program

/* File: proto.c Demonstrate the need for prototypes This is the buggy version. */ #include <stdio.h> /* No prototypes in this version */ 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); } /* The function Add3 adds 3.0 to the value passed into y and returns that sum back to the calling function. */ double Add3 (double y) { double z; z = y + 3.0; return (z); }

When trying to compile

retriever[102] cc proto.c cfe: Error: proto.c, line 28: redeclaration of 'Add3'; previous declaration at line 14 in file 'proto.c' double Add3 (double y) -------^ cfe: Error: proto.c, line 28: Incompatible function return type for this function. double Add3 (double y) ------------^ retriever[103]

The Fixed Program

/* File: proto2.c Demonstrate the need for prototypes This is the corrected version. */ #include <stdio.h> /* Include the prototype in this version */ double Add3(double); 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); } /* The function Add3 adds 3.0 to the value passed into y and returns that sum back to the calling function. */ 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'99 | lectures | news | help

Last Modified - Wednesday, 17-Feb-1999 14:24:58 EST