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

做~自己de王妃 提交于 2019-12-05 23:31:43

问题


Compiling this code using g++ -std=c++17 -Wall -pedantic main.cpp doesn't produce any warnings:

#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?


回答1:


I did some research and I found that -Wall doesn't warn about type conversion issues.

Instead, use the flag -Wconversion in order to get a warning about potential type conversion issues.

Remarks:

For the users of VC++, /W4 will warn you about possible loss of data during type conversions



来源:https://stackoverflow.com/questions/52443036/why-doesnt-c-show-a-narrowing-conversion-error-when-casting-a-float-to-a-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!