c - 将 float 分配给 int 变量不会导致警告

标签 c types warnings implicit-conversion

因此,给定以下代码:

int main(void) {
  int i;
  i = 12.1234;
  i++;
  return 0;
}

我编译了代码,我期望并希望编译器给我一个警告,但它没有。我的编译器配置错误吗?有没有办法让我的编译器发出警告?

这是我用的

cc -Wall test.c

最佳答案

既然你确认你的编译器是 gcc 那么你可以使用 -Wconversion应提供与此类似的警告的标志:

warning: conversion to 'int' alters 'double' constant value [-Wfloat-conversion]
i = 12.1234;
    ^

将浮点值转换为 int 是完全有效的,它会丢弃小数部分,只要该值可以表示,否则就会出现未定义的行为。 C99 标准草案在 4.9 部分涵盖了这一点 float 转换:

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.

关于c - 将 float 分配给 int 变量不会导致警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24915712/

相关文章:

c - pow 函数的奇怪行为

c - 使用复数数组

c - 分配还是不分配。大小 1 错误的读取无效。 【凝视2小时】

"delete-event"信号的回调函数传递了错误的变量值

javascript - 删除 |来自 Typescript 类型的 null

types - LISP:该值不是预期的类型 LIST

python - 为什么 mypy 推断公共(public)基类型而不是所有包含类型的联合?

c警告[Pe188] : enumerated type mixed with another type

java - 奇怪的 "Resource leak: stream is never closed"如果在循环中抛出异常,则使用 try-with-resources

ssl - 忽略 Grunt 中无效的自签名 ssl 证书警告