cstdoutheader-filesobject-code

When the declaration of the function is in a traditional style, why isn't the output correct?


I have declared the function pow in the traditional way of declaration in C. However, the output of function is incorrect. I don't need to include math.h here as I am declaring the function and the object code for it is already present. Here is my code:

#include<stdio.h>

double pow();           //traditional declaration doesnt work, why??

int main()
{
    printf("pow(2, 3) = %g", pow(2, 3));
    return 0;
}

The output for the above is 1 whereas it should be 8. Please help me with it.


Solution

  • traditional declaration doesnt work, why??

    Because without a prototype, those two ints you provided don't get converted to the doubles that pow actually accepts. With "traditional" declarations you must painstakingly make sure you provided exactly the type of arguments expected by the function, or you'll have yourself undefined behavior in your program.

    This is one reason to favor prototypes, and to actually use the standard library headers that provide them for standard functions.