So, given the following code:
int main(void) {
int i;
i = 12.1234;
i++;
return 0;
}
I compiled the code and I expected and wanted the compiler to give me a warning, but it didn't. Is my compiler configured wrong? Is there a way to make my compiler give warning?
This is what I used
cc -Wall test.c
You can safely assign a floating point variable to an integer variable, the compiler will just truncate (not round) the value. At most the compiler might give you a warning, especially if assigning from e.g. a double or bigger type.
So you cannot store a float value in an int object through simple assignment. You can store the bit pattern for a floating-point value in an int object if the int is at least as wide as the float , either by using memcpy or some kind of casting gymnastics (as other answers have shown).
Any integral numeric type is implicitly convertible to any floating-point numeric type. There are no implicit conversions to the byte and sbyte types. There are no implicit conversions from the double and decimal types. There are no implicit conversions between the decimal type and the float or double types.
To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.
Since you confirmed your compiler is gcc
then you can use the -Wconversion flag which should provide a warning similar to this:
warning: conversion to 'int' alters 'double' constant value [-Wfloat-conversion]
i = 12.1234;
^
Converting a floating point value to int is perfectly valid it will discard the fractional part and as long as the value can be represented, otherwise you have undefined behavior. The C99 draft standard covers this in section 4.9
Floating-integral conversions:
A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.
A float value can be assigned to an integer variable but an implicit conversion occurs when compiler forces a float value to be assigned as an integer.
The digits after the decimal notation in the float value get lost after assigning a float to an integer.
Edit: casting -> conversion
Thanks R..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With