简体   繁体   English

为什么在将float转换为char时C ++没有显示缩小的转换错误?

[英]Why doesn't C++ show a narrowing conversion error when casting a float to a char?

Compiling this code using g++ -std=c++17 -Wall -pedantic main.cpp doesn't produce any warnings: 使用g++ -std=c++17 -Wall -pedantic main.cpp编译此代码不会产生任何警告:

#include <iostream>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
  for (int i = 0; i < 100; ++i) {
    float x = 300.0 + rand();
    char c = x;
    std::cout << c << std::endl;
  }

  return 0;
}

Shouldn't it produce a narrowing error? 它不应该产生缩小误差吗?

I did some research and I found that -Wall doesn't warn about type conversion issues. 我做了一些研究,我发现-Wall没有警告类型转换问题。

Instead, use the flag -Wconversion in order to get a warning about potential type conversion issues. 而是使用标志-Wconversion来获取有关潜在类型转换问题的警告。

Remarks: 备注:

For the users of VC++, /W4 will warn you about possible loss of data during type conversions 对于VC ++的用户, /W4会警告您在类型转换期间可能丢失数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM