-2

The following code snippet causes the code to bail out prematurely. My question is why my system still shows Program finished with exit code 0.

#include <stdio.h>

int main(void) {
   int divisor = 0;
   int dividend = 0;
   int quotient = 0;

   printf("BEGIN\n");
   quotient = dividend / divisor;
   printf("END\n"); // This statement does not execute
   
   return 0;
}
Sandeep
  • 1,245
  • 1
  • 13
  • 33
  • 1
    How did you run it? From inside an IDE or from a terminal window? I suspect it was from an IDE and the IDE isn't being very helpful, but I might be wrong. – Jonathan Leffler Jan 31 '22 at 17:19
  • @JonathanLeffler Yes it was run from inside an IDE. – Sandeep Jan 31 '22 at 17:21
  • In some cases it might work, in some it might not but it's UB. – Irelia Jan 31 '22 at 17:21
  • 1
    Try running it from a terminal window. On a Unix-like system, you might try: `./your_program; echo $?`. This will run the program and you'll see any error messages from the runtime system. It will then print the shell's interpretation of the exit status. It will likely be a number such as 136 (128 + 8, where 8 is SIGFPE — floating-point exception; integer divide by zero is the primary reason for getting that signal these days). Your IDE may be misinterpreting the exit status of the command window it runs, etc. Which IDE are you using, on which o/s? – Jonathan Leffler Jan 31 '22 at 17:26

1 Answers1

6

This is undefined behavior. The compiler is free to do whatever it feels is right in this situation, for example terminating with exit code 0.

littleadv
  • 20,100
  • 2
  • 36
  • 50