Nagaraj Tantri
Nagaraj Tantri

Reputation: 5260

error of integer overflow

This the part of my OpenGL code, I am getting an error for :

struct Ball {
    float x;
    float y;
    float rot;
    float dir;
    bool rmv;
    Ball* next;
};

Ball* curBall;
void addBall() {
    if (balls==NULL) {
        balls=new Ball;
        balls->next=NULL;
        curBall=balls;
    } else {
        curBall->next=new Ball;
        curBall=curBall->next;
        curBall->next=NULL;
    }
    curBall->x=((float)rand()/(float)(RAND_MAX+1))*(ww-1) +1;
    curBall->y=((float)rand()/(float)(RAND_MAX+1))*(wh-1) +1;
    curBall->dir=((float)rand()/(float)(RAND_MAX+1))*(2*PI-1) +1;
    curBall->rot=((float)rand()/(float)(RAND_MAX+1))*(359) +1;
    curBall->rmv=false;
}

error :
In function ‘void addBall()’:
file.cpp:120: warning: integer overflow in expression
file.cpp:121: warning: integer overflow in expression
file.cpp:122: warning: integer overflow in expression
file.cpp:123: warning: integer overflow in expression

Upvotes: 3

Views: 2845

Answers (4)

mmmmmm
mmmmmm

Reputation: 32720

It could depend on your compiler if RAND_MAX == MAX_INT then RAND_MAX+1 will overflow.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490768

I'd guess your RAND_MAX is equal to your INT_MAX, so all your RAND_MAX+1 pieces are overflowing. Since those are both constants, the compiler can detect it at compile time.

Upvotes: 2

Paul R
Paul R

Reputation: 213200

It's probably RAND_MAX + 1 that's overflowing, since RAND_MAX may well be == INT_MAX.

Upvotes: 2

Amber
Amber

Reputation: 527508

Try converting RAND_MAX to a float before adding to it.

curBall->x=((float)rand()/( ((float)RAND_MAX) +1))*(ww-1) +1;

et cetera. RAND_MAX is often equal to INT_MAX, the largest value an integer could hold, thus adding 1 to it while it's still considered an integer pushes it over the integer limit.

Upvotes: 13

Related Questions