17

I wrote a simple program to find the Sum, average, biggest and smallest number of 3 numbers. It lets the user to input three (integer) numbers and return the sum, average, max and min. It has no errors but a warning. Here is my source code:

main.c:

#include <stdio.h>

int main()
{
    int num1, num2, num3, sum, max, min, avg;

    printf("Enter Three \"Integer\" Numbers:");

    scanf("%i%i%i", &num1, &num2, &num3);

    sum = summation(&num1, &num2, &num3);
    avg = average(&sum);
    max = max_val(&num1, &num2, &num3);
    min = min_val(&num1, &num2, &num3);

    printf("Sum: %i Avg: %i MAX: %i MIN: %i", sum, avg, max, min);

    return 0;
}

int summation(int *n1, int *n2, int *n3)
{
    int s;
    s = *n1 + *n2 + *n3;

    return s;
}

int average(int *s)
{
    int a;
    a = *s / 3;

    return a;
}

int max_val(int *n1, int *n2, int *n3)
{
    int MAX;

    if (*n1 > *n2) MAX = *n1;
    else if (*n2 > *n3) MAX = *n2;
    else MAX = *n3;

    return MAX;
}

int min_val(int *n1, int *n2, int *n3)
{
    int MIN;

    if (*n1 < *n2) MIN = *n1;
    else if (*n2 < *n3) MIN = *n2;
    else MIN = *n3;

    return MIN;
}

I think there is no need to make a header file because all functions are in type of "int".

When I compile this

gcc main.c -o test

It says

main.c: In function 'main':
main.c:34:5: warning: implicit declaration of function 'summation' [-Wimplicit-function-declaration]

Why this warning? I can't find any wrong in that declaration. What's that?

0xEDD1E
  • 1,172
  • 1
  • 13
  • 28

1 Answers1

34

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...
pb2q
  • 58,613
  • 19
  • 146
  • 147
  • ah, yeah, I got it. That means it should be broken into .c pieces and compile them together, no? Thank you! – 0xEDD1E Aug 26 '12 at 03:23
  • 2
    @0xEDD1E More specifically, it's like a book. You read from top to bottom. If you read the bottom before the top, you don't understand the plot. Same goes for C and C++ programs. Everything must literally be defined prior to use... variables, functions, structs, enums, etc. – Inisheer Aug 26 '12 at 03:34
  • 3
    In the 1990 version of the C standard, there's an implicit declaration and the function is assumed to return `int`. In the 1999 version and later, there is no "implicit int" rule; calling a function with no visible declaration is a constraint violation. – Keith Thompson Aug 26 '12 at 03:59