Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide by 0 warning

I have been working on an application and because images were acting up weird I decided to switch the Wall flag on to see if anything odd was going on. It revealed a new warning:

character.cpp(364): warning C4723: potential divide by 0

The odd thing is that there is no division going on anywhere around that point:

//Currently hp is always equal to 30
for (int i = 0; i < hp; i++) {
    int startXPos = i*12 + 40;
    if (i == hp-1) {
        gfx.DrawLine(10+startXPos,15,10+startXPos,40,245,245,245); //This line
        //This function expects: int, int, int, int, int, int, int
    }
}

Now this warning only occurs when I compile with the /Ox - flag (Full Optimization). When compiling with /Od (No Optimization) I do not receive the warning.

My question is: should I just ignore this warning (suppress it perhaps)? Or should I be worried? And what causes this?

Update:

Part of the DrawLine function:

int dx = x2 - x1;
int dy = y2 - y1;

if( dy == 0 && dx == 0 ) {
    //1 pixel line
}
else if( std::abs( dy ) > std::abs( dx ) ) {
    if( dy < 0 ) {
        std::swap(x1,x2);
        std::swap(y1,y2);
    }
    float m = static_cast<float>(dx / dy);
    //No different/more division past this point
like image 786
Floris Velleman Avatar asked Jan 18 '26 13:01

Floris Velleman


1 Answers

The warning happens because you have a possibility of "dy" being zero:

int dy = y2 - y1;

And 'dy' is used in a divide:

float m = static_cast<float>(dx / dy);

If 'y2' and 'y1' have the same value, then its the same as doing this:

float m = static_cast<float>(dx / 0);

Hard to know how to fix properly because we do not have the full algorith, but as a minimum: check dy before using it as a divisor. e.g (quick n dirty example):

float m = static_cast<float>(dy ? dx/dy : 0);     // 0 depends on your algorithm...

Or you may clip the line all together, interpreting y1 & y2 being equal to an infinitely small line which should not be drawn at all, in which case you would exit the DrawLine function immediately if dx or dy is equal to 0.

like image 168
Chris Avatar answered Jan 20 '26 03:01

Chris