代码之家  ›  专栏  ›  技术社区  ›  Kristopher Ives

当将浮点转换成字符时,为什么C++不显示一个缩小的转换错误?

  •  7
  • Kristopher Ives  · 技术社区  · 7 年前

    使用编译此代码 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;
    }
    

    它不应该产生缩小误差吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Simo    7 年前

    我做了一些研究发现 -Wall

    相反,使用标志 -Wconversion 以获取有关潜在类型转换问题的警告。

    评论:

    对于VC++的用户来说, /W4 将警告您在类型转换期间可能丢失数据