Search code examples
cintegerconstantsdoubleundefined-behavior

Assigning a double to an integer in C causes the program to crash


I'm developing a visual application in C to render some firework explosions as a learning project. To control how fast they go up, I have a speed variable like this:

typedef struct Firework
{
    //Other data on the struct
    int speed;
} Firework;

I also needed to initialize the speed variable for every firework, so the next piece of code was this one:

// this works:
const int maxSpeed = 1;

// however if replaced with this, then the program will crash inside the loop
// const int maxSpeed = 0.5;

Firework fireworks[5] = { 0 };
for(size_t i = 0; i < sizeof(fireworks) / sizeof(fireworks[0]); i++)
{
    fireworks[i].speed = (rand() % maxSpeed) + 1;
}

The problem is, I assigned the value 0.5 to maxSpeed by mistake and the result was program starting and then terminating almost immediately when I tried to use maxSpeed. I realized the mistake and fixed it but unfortunately I couldn't find much online and there are a few things I don't understand:

Is using a double to initialize an integer an undefined behaviour in C?

If so, why didn't I get any error or warning messages from my compiler? (Mingw-w64)

What was causing the application to terminate (sometimes even with an exit code of 0) instead of just behaving weirdly?

Did the maxSpeed variable being const had anything to do with this?


Solution

  • 0.5 converted to integer is zero. Then you use the modulo % operator you divide the result of the rand function by zero - which of course will terminate the program on most hardware platforms. It is Undefined Behaviour.