Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

gcc

narrowing

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?

like image 302
Kristopher Ives Avatar asked Sep 21 '18 11:09

Kristopher Ives


People also ask

How do you fix narrowing conversion 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.

What is a narrowing conversion?

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 .

Is int to float narrowing?

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


1 Answers

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

like image 195
Simo Avatar answered Oct 12 '22 11:10

Simo