Reputation: 13
Why is my simple C program printing "hello world" and being compiled with no errors and is running fine when I gave a floating point number next to return statement? Shouldn't it be an error to do so?
Here is my code:
#include<stdio.h>
int main()
{
printf("hello world");
return 2.1;
}
Upvotes: 1
Views: 344
Reputation: 11
This is normal as the value well be implicitly converted to your declared type. the compiler will not mind but you'll get unexpected results at the runtime in general and in this specific case the casting to (int).
Upvotes: 0
Reputation: 8494
For the same reason of
int main(void)
{
// ...
int x = 2.1;
// ...
return x;
}
This is called implicit conversion.
Upvotes: 3
Reputation: 404
The return code will be casted automatically on return. The long version is
return (int) 2.1;
Upvotes: 1
Reputation: 1325
Your code will return an integer because the compiler will take care of casting the float into an integer.
Upvotes: 0
Reputation: 781751
When you return a different type from the declared type of the function, the value is automatically converted to the declared type. So it's equivalent to doing:
return (int) 2.1;
Upvotes: 3