Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning float into int variable causes no warning

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

like image 803
Le Curious Avatar asked Jul 23 '14 16:07

Le Curious


People also ask

What happens if you assign a float to an int?

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.

Can we store float into integer variable?

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).

Can float be implicitly converted to int?

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.

How do I assign an int to a float?

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.


2 Answers

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.

like image 110
Shafik Yaghmour Avatar answered Oct 19 '22 17:10

Shafik Yaghmour


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..

like image 5
Igor Avatar answered Oct 19 '22 15:10

Igor