5

I've been looking for a solution to this but haven't found anything that will help. I'm getting the following errors:

Implicit declaration of function 'sum' is invalid in C99
Implicit declaration of function 'average' is invalid in C99
Conflicting types for 'average'

Has anyone experienced this before? I'm trying to compile it in Xcode.

#import <Foundation/Foundation.h>


    int main(int argc, const char * argv[])
    {

       @autoreleasepool
       {
          int wholeNumbers[5] = {2,3,5,7,9};
          int theSum = sum (wholeNumbers, 5);
          printf ("The sum is: %i ", theSum);
          float fractionalNumbers[3] = {16.9, 7.86, 3.4};
          float theAverage = average (fractionalNumbers, 3);
          printf ("and the average is: %f \n", theAverage);

       }
        return 0;
    }

    int sum (int values[], int count)
    {
       int i;
       int total = 0;
       for ( i = 0; i < count; i++ ) {
          // add each value in the array to the total.
          total = total + values[i];
       }
       return total;
    }

    float average (float values[], int count )
    {
       int i;
       float total = 0.0;
       for ( i = 0; i < count; i++ ) {
          // add each value in the array to the total.
          total = total + values[i];
       }
       // calculate the average.
       float average = (total / count);
       return average;
    }
Carolus
  • 477
  • 4
  • 16
uplearned.com
  • 3,393
  • 5
  • 44
  • 59
  • Check this answer, worked like a charm for me! https://stackoverflow.com/a/46221365/3063226 – Heitor Nov 10 '17 at 05:38

2 Answers2

10

You need to add declaration for these two functions, or move the two function definitions before main.

Lei Mou
  • 2,562
  • 1
  • 21
  • 29
  • Nope. Check https://stackoverflow.com/a/46221365/3063226, the explanation and the solution are right there! – Heitor Nov 10 '17 at 05:39
7

The problem is that by the time the compiler sees the code where you use sum it doesn`t know of any symbol with that name. You can forward declare it to fix the problem.

int sum (int values[], int count);

Put that before main(). This way, when the compiler sees the first use of sum it knows that it exists and must be implemented somewhere else. If it isn't then it will give a liner error.

imreal
  • 10,178
  • 2
  • 32
  • 48
  • I fixed it thanks you point me in the right direction. I also had to include: int sum (int values[], int count); float average (float values[], int count ); above main() – uplearned.com Dec 13 '12 at 23:20
  • 1
    I fixed it Nick thanks. I aslo had to add : float average (float values[], int count ); – uplearned.com Dec 13 '12 at 23:24