papercuts
papercuts

Reputation: 1438

Error: "Implicit declaration of function..." on all my functions

Here's the code

main()
{
    short sMax = SHRT_MAX;
    int iMax = INT_MAX;
    long lMax = LONG_MAX;

    // Printing min and max values for types short, int and long using constants
    printf("range of short int: %i ... %i\n", SHRT_MIN, SHRT_MAX);
    printf("range of int: %d ... %d\n", INT_MIN, INT_MAX);
    printf("range of long int: %ld ... %ld\n", LONG_MIN, LONG_MAX);

    // Computing and printing the same values using knowledge of binary numbers
    // Short
    int computed_sMax = computeShort() / 2;
    printf("\n Computed max and min short values: \n %i ... ", computed_sMax);

    int computed_sMin = (computeShort()/2 + 1) * -1;
    printf("%i\n", computed_sMin);

    //Int
    int computed_iMax = computeInt() / 2;
    printf("\n Computed min and max int values: \n %i ... ", computed_iMax);

    int computed_iMin = computeInt() / 2;
    printf("%i", computed_iMin);



    return 0;
}

int computeShort()
{
    int myShort = 0;
    int min = 0;
    int max = 16;

    for (int i = min; i < max; i++)
    {
        myShort = myShort + pow(2, i);
    }

    return myShort;
}

int computeInt()
{
    int myInt = 0;
    int min = 0;
    int max = 32;

    for (int i = min; i < max; i++)
    {
        myInt = myInt + pow(2, i);
    }

    return myInt;
}

Upvotes: 3

Views: 16596

Answers (2)

user529758
user529758

Reputation:

You have to declare the functions before you use them:

int computeShort(); // declaration here

int main()
{
    computeShort();
}

int computeShort()
{
    // definition here
}

An alternative, but less advisable approach is to define the functions before main, since the definition serves as declaration as well:

int computeShort()
{
    // return 4;
}

int main()
{
    computeShort();
}

But generally it's better practice to have a separate declaration for the functions used, because then you aren't obliged to maintain a certain order in the implementation.

Upvotes: 6

unwind
unwind

Reputation: 399803

You must declare functions before calling them. This is true even for parts of the standard library.

For instance, printf() is declared by doing:

#include <stdio.h>

For your own functions, either:

  • Move the definitions to above main(); the definitions serve as declarations too.
  • Add prototypes before the calls, typically right before main():

    int computeShort();

Also, note that

  • Local functions should be declared static.
  • Functions not accepting any argument should have an argument list of (void), not () which means something else.

Upvotes: 3

Related Questions