I have code like this:
#include <stdio.h>
#include <stdint.h>
int main() {
uint8_t result = 0;
uint8_t a = 0;
printf("Trying to divide by %d...\n", a);
result = (1/a != 0);
printf("%d\n", result);
return 0;
}
I have tried this in online compiler here: https://www.mycompiler.io/new/c
And this is the result:
[Execution complete with exit code -8]
I expected "Trying to divide by 0..." to be printed out, and then application should exit.
But the application exits before it prints anything.
Is it normal C behavior or some glitch of online compiler?
CodePudding user response:
I can see two possible explanations here
First, it's important to know that undefined behavior can time travel back in time. There is no guarantee that the program will run fine until the problematic line. This may occur because the compiler might think that it would be better to reorder things like this:
uint8_t a = 0;
uint8_t result = (1/a != 0);
printf("Trying to divide by %d...\n", a);
The compiler is allowed to do this, because it's allowed to assume that division by zero will never happen.
Second, it could be the case that the output needs to be flushed. Whenever you want to make sure that a printout gets visible on screen before doing something else, use fflush(stdout)
. It might make a difference if you do this:
printf("Trying to divide by %d...\n", a);
fflush(stdout);
result = (1/a != 0);