1

I want to manipulate the output of lex. There is only one write to yyout, in the ECHO macro. The macro is surrounded by "#ifndef ECHO", so I am replacing it with my desired action. However, I want to be sure to correctly replicate the original lex behavior. Lex defines ECHO to this code fragment:

do { 
    if (fwrite( yytext, yyleng, 1, yyout )) {
        } 
    } while (0)

Can anyone guess why the output is not simply "fwrite(...)"?

Robert R Evans
  • 177
  • 1
  • 11
  • 1
    See [this question](http://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for) – sjsam Apr 21 '16 at 13:57

1 Answers1

1
do { .. } while (0)

is a convenient way to #define a multi-statement operation as pointed out by this.

By

if (fwrite( yytext, yyleng, 1, yyout ))

I believe you're given an option to deal with fwrite failure.

Here you call fwrite with just 1 element of size yyleng. Considering that fwrite returns the total number of elements written, the possible return values are just 0 and 1 - 0 indicating any failure and 1 indicating success.

Ideally(or actually it is?), it should have been

if (!fwrite( yytext, yyleng, 1, yyout ))

I'm guessing this because, only block is given to write the fallback/logging code.

Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • That explains the do loop - thx for the link. But it doesn't explain the empty if statement. The code fragment is the code in its entirety - no elisions. – Robert R Evans Apr 25 '16 at 13:11
  • 1
    @RobertREvans : By the way, did you compile lex from source? It's worth checking its documentation for this. :) – sjsam Apr 25 '16 at 14:37