简体   繁体   中英

C Program doesn't give error when function prototype is missing

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM