[英]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.