为什么GCC警惕这种隐式转换? [英] Why does GCC warn against this implicit conversion?

查看:523
本文介绍了为什么GCC警惕这种隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GCC警告我说,以下code的一块包含可能改变值的隐式转换:

GCC warns me that the following piece of code contains an implicit conversion that may change a value:

#include <stdlib.h>
float square = rand();

但是,以下不会产生任何警告:

However, the following does not yield any warning:

float square = 100;

由GCC给出的警告是如下:

The warning given by GCC is a follows:

tests/ChemTests.cpp:17:23: error: conversion to ‘float’ from ‘int’ may alter its value

我不明白,为什么前者将给予警告,因为兰特()正常申报并返回一个 INT ,就像 100 整数文字。

I don't understand why the former would give a warning, since rand() is properly declared and returns an int, just as the 100 integer literal.

为什么第一行给出一个编译器警告,但不是第二个,即使双方都有从 INT 的隐式转换为浮动

Why does the first line give a compiler warning but not the second, even though both have an implicit conversion from intto float?

推荐答案

GCC会发出这样的警告时precision的损失可能导致投。 (换句话说,该值可以是改变)

GCC emits this warning when a loss of precision may result from the cast. (in other words, the value may be "altered")

在第一种情况下,兰特()返回 INT 。由于可以存储在 INT 重新presentable为浮动并不是所有的值,它会散发出此警告。

In the first case, rand() returns an int. Since not all values that can be stored in an int are representable as a float, it will emit this warning.

在第二种情况下,100可以安全地铸造到浮动没有任何precision损失。

In the second case, 100 can be safely casted to a float without any precision loss.

这篇关于为什么GCC警惕这种隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆