0

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?

HeroOfSkies
  • 3
  • 1
  • 3
  • Assigning or initialing an integer variable with a floating point value *truncates* the value. So `0.5` becomes `0`. And division by `0` is never going to lead to nice stuff happening. – Some programmer dude Jan 16 '21 at 11:33
  • @Someprogrammerdude I have no idea how I did not see that. Thank you very much :) Turns out I was going crazy for no reason... – HeroOfSkies Jan 16 '21 at 11:38
  • The question is not useful by itself. The code that crashes is not presented in the question. You must use a debugger or other debugging methods to try and isolate the part of the code that **actually** crashes and present it in the question so that it truly contains a [mre]. – Antti Haapala -- Слава Україні Jan 16 '21 at 11:45
  • @AnttiHaapala I actually have used a debugger and posted the code that causes the program to crash, it's the initialization of the Firework structure's speed variable: "...then terminating almost immediately when I tried to use maxSpeed". – HeroOfSkies Jan 16 '21 at 12:04
  • Ah 0.5... i.e. I need to read the code more carefully. – Antti Haapala -- Слава Україні Jan 16 '21 at 12:08

1 Answers1

0

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.

0___________
  • 60,014
  • 4
  • 34
  • 74