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