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?
If you make a narrowing conversion intentionally, make your intentions explicit by using a static cast. Otherwise, this error message almost always indicates you have a bug in your code. You can fix it by making sure the objects you initialize have types that are large enough to handle the inputs.
A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values. For example, a fractional value is rounded when it is converted to an integral type, and a numeric type being converted to Boolean is reduced to either True or False .
- in this sense it is called narrowed. Though float has wider range than int, it has less precision. Besides, floating point representation is approximation - that is, it does not represent exact number (except for power of 2). In that sense, the int is also narrowed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With