If read the compiler warnings carefully says
warning: type of 'w' defaults to 'int' [-Wimplicit-int]
1 | double bmi(w,h){
| ^~~
<source>:1:8: warning: type of 'h' defaults to 'int' [-Wimplicit-int]
So, if you declare the data type of w
and h
as doubles
, then it will be fine.
This is a kind of old-style function and can be turned on by using -Wold-style-definition
flags when compiling.
Now, you will say that you are creating a double
variable bmi
in your function bmi
, so it should return a proper value. But it doesn't because any operation between two int
s will always return an int
.
Use -std=c17
flags to keep yourself upto-date with C standards.
And that is UB
Undefined Behaviour.
Main context from cppreference.com
about UB:
undefined behavior - there are no restrictions on the behavior of the program. Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, modification of the same scalar more than once in an expression without sequence points, access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.
The compilers are required to issue diagnostic messages (either errors or warnings) for any programs that violates any C syntax rule or semantic constraint, even if its behavior is specified as undefined or implementation-defined or if the compiler provides a language extension that allows it to accept such program. Diagnostics for undefined behavior are not otherwise required.
Correct C programs are free of undefined behavior, compilers may produce unexpected results when a program that actually has UB is compiled with optimization enabled:
I also noticed that your variable and function name are same, which is also a problem. So, use any other name like val
or bmi_val
.
You are not checking the result of scanf()
function, it checks for any sort of bad format.
Your function should be TRY IT ONLINE
:
double bmi(double w, double h)
{
return w / h;
}
Recommeded GCC
flags for warnings:
-g -W -Wall -Wextra -Wuninitialized -Wstrict-aliasing -ggdb3 -std=c17 -Wextra -pedantic -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Wshadow