gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:54:59 26 4
gpt4 key购买 nike

因此,给定以下代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com