1

I read that every function in C should have a prototype and also that if a function takes in arguments or returns a value, their data types should be mentioned in both the prototype and the definition. However, I recently tried a piece of code which involved a call to a user defined function, which didn't satisfy the above requirements. Yet the program didn't throw any errors, although the result was incorrect. Can anyone provide with an explanation?

The code I tried was as follows:

#include<stdio.h>

int main(){

printf("%f",sum(3.2, 5.6));
return 0;
}

sum(a, b){
   return a+b;
}

The code compiles and runs successfully with the output being 0.000000. The process exits with an exit code of 0. I ran the code on various online compilers.

Coder
  • 2,153
  • 1
  • 16
  • 21
ikubuf
  • 21
  • 3
  • https://stackoverflow.com/questions/11881300/why-the-error-of-calling-the-function-before-being-declared-is-not-shown – melpomene Jul 06 '19 at 14:01
  • 2
    Btw, you're making use of implicit int. So your function actually looks like `int sum(int a, int b)` which means you trying to print an `int` with `%f` is undefined behaviour. – DeiDei Jul 06 '19 at 14:04
  • @DeiDei I didn't get you – ikubuf Jul 06 '19 at 14:09
  • But what I did understand from the above link is that it is primarily because the legacy C language allowed for function use even before declaration and that most of the compilers still allow you to do so. Although, I still am confused about why the result is 0.000000. – ikubuf Jul 06 '19 at 14:14
  • Not **all** functions require a prototype, though it doesn't make sense for non-`static` functions to not have one, (in the `.h` file.) If it were a `static` function and one had declared it before calling, than I would argue that prototyping is, at least, unnecessary. (And `main` doesn't need one.) – Neil Jul 25 '19 at 20:17

1 Answers1

3

If you do not specify a return type or parameter type, C will implicitly declare it as int.

This is a "feature" from the earlier versions of C (C89 and C90), but is generally considered bad practice nowadays. C99 standard (1999) does no longer allow this.

Coming to the point on why it is printing 0.0000, it is because the function returns an int which requires a type specifier %d but you are using an %f which is a type specifier for double. Refer this stackoverflow post for further explaination printing int using %f format specifier

Coder
  • 2,153
  • 1
  • 16
  • 21