0

In the following two codes I cannot understand the problem. First code is:

#include <stdio.h>
main() {

    int num1, num2;

    scanf("%d%d", &num1, &num2);

    printf("I LOVE MY INDIA\n"); //here is '\n' after the statement
    printf("%d", num1/num2);

    return 0;
}

Here if the inputs are num1=2 and num2=0 then in gcc compiler the output is:

I LOVE MY INDIA
Floating point exception (core dumped)

But for the second code:

#include <stdio.h>
main() {

    int num1, num2;

    scanf("%d%d", &num1, &num2);

    printf("I LOVE MY INDIA"); //here is no '\n'
    printf("%d", num1/num2);

    return 0;
}

For same input as before this is showing:

Floating point exception (core dumped)

In between these two codes there is only one difference. In the 1st one there is a \n after I LOVE MY INDIA and in the 2nd code there is no \n. Please explain why I LOVE MY INDIA is not being displayed in the 2nd code.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
biswasJUCSE
  • 381
  • 1
  • 13

1 Answers1

6

By default, the standard output (stdout) is line buffered.

In first case, the newline \n in the printf() causes the output buffer to be flushed to the output before the crash happens. So, you got to see the print statement.

OTOH, in the second case, lack of the \n causes the buffer to hold the data, and the next statement causes the exception and an abnormal termination of the program. So, the buffered data did not get a chance to be flushed to the output terminal. Hence, you got no visual output.

That said, a division by zero causes undefined behavior and strictly speaking, your program cannot be relied upon to produce any expected output.

Sourav Ghosh
  • 127,934
  • 16
  • 167
  • 234