Hazard error(C++ Fundementals course)

I checked to make sure I did everything the same way in the video but every time I run my project I cant see my hazard, and im getting a warning about “narrowing conversion of ‘(nebula.Texture::width / 8)’ from ‘int’ to ‘float’ [-Wnarrowing]” Could someone help me with this.

Hi Bea8st,

Thankfully this a warning so you can ignore it if you like, but allow me to explain what it is and what you can do to clear it.

A narrowing conversion occurs when converting from one data type to another may result in data loss. You’ll see this most often when going from integers to floats, doubles to floats, or long to double.

In all cases, this is because the maximum number that can be held is higher than the maximum number of the type you’re converting to. This is fairly easily explained in most cases since you’re going from a data type that holds more bits to one that holds less.

However, what about converting from integer to float? Technically integer and float both use 4 bytes of data to store values, so it would seem logical that they can store the same maximum number. In practice, though, floats use some of that space to account for the decimal, so it’s maximum number is 2^23 (in both directions) while an integer has a maximum value of 2^32 (also both directions). Which means higher numbers will end up getting lost in the conversion and truncated down to 2^23.

Now, in gamedev it’s rare to reach numbers this high (unless you’re Nippon Ichi and you’re working on the next Disgaea). But the compiler still wants to warn you that this could happen.

So how do we clear it? The easiest solution here is to modify the integer representation so that it’s a float instead. Which means:

changing nebula.width / 8 into nebula.width / 8.0f since the width value in Texture2D will always be of type float and we can’t change that easily, we’ll change the value we’re dividing it by to be a float instead.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms