0

I've a piece of code for a compiler for basic arithmetic (add, diff). In my mparse.y yacc file, I've read input from a file in main function. To invoke parsing, I've put the condition as follows:

if(yyparse()==0)
  fprintf(stderr,"Parsing complete.");

the last statement of yyparse, after completion is supposed to be:

printf("The last statement of yyparse");

The problem is, if I use fprintf(), I get the following absurd output:

Parsing Complete
The last statement of yyparse.

Whereas, if I use printf instead of fprintf, I get the normal output.

The last statement of yyparse
Parsing complete.

Shouldn't the second option be correct, ie, all the statements of yyparse should be executed first and then the printf after if? Why this weird behaviour?

1 Answers1

1

This is the result of stderr and stdout being buffered differently. It has nothing to do with yyparse.

Stdout is normally line buffered, which means that output is kept in a buffer until a newline is printed or the file descriptor is closed.

Stdout is normally unbuffered, so its output is immediate.

If you mix output to stdout and stderr, the order of actual output can be inverted.

By the way, if you just want to output a fixed string, it is better to use puts(msg) (to print to stdout) or fputs(msg, file). puts automatically outputs a newline at the end of the string; if for some reason you don't want that, use fputs(msg, stdout)

rici
  • 234,347
  • 28
  • 237
  • 341