assigning float into int variable causes no warning

前端 未结 3 810
感情败类
感情败类 2021-01-18 07:27

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 t

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 07:53

    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.

提交回复
热议问题