I'm experimenting with flex to try to gain a better understanding of how it works. I have this in the lex (.l) file:
%option noyywrap
%%
"a" printf("Found an \"a\"");
%%
int main()
{
printf("This is working");
return 0;
}
Ignoring the single rule for now (unless it's somehow the cause) I want to know why the printf statement in the main() function isn't doing anything. After digging through the generated lex.yy.c file, I suspect the line
yyout = stdout;
might be the cause, although I can't say why (and I couldn't find anything when searching for why flex does this)
I'm hoping to understand not only what this means in terms of C code, but why flex does this. It seems to be either supressing or redirecting the output (to the yacc code maybe?). I would appreciate any explanations or links to some information.
(Unless this is just my C code being somehow broken)
If you use puts
instead of printf
then a newline will be appended automatically for you. There's no point in using printf
to print a constant string which doesn't include formatted conversions.
You could do that yourself, of course, by changing it to
printf("This is working\n")
or:
printf("%s\n", "This is working.");
Or even better:
fprintf(stderr, "%s\n", "This is working.");
(See below.)
If you don't output a newline, your output will probably just stay in the stdio buffer (although it should be flushed when stdout is closed). Also, some IDEs behave badly when the last bit of output is not terminated with a newline. (Swallowing the characters is a common symptom.) All in all, it's best to follow the following guidelines.
In general:
You should always end printed lines with new lines.
You should be aware of the consequences of stdout
line buffering, which is that in common cases, not terminating output to stdout
means that it won't be presented right away.
And you should get in the habit of using stderr
instead of stdout
for logging messages, even if they are not strictly speaking errors, leaving stdout
for the processed output of your program (in case you want to pipe the output into another utility). Unlike stdout
, stderr
is (by default) usually unbuffered, so output is presented immediately. (But you should still put a newline at the end, rather than leaving the cursor dangling in the middle of the line.)
fputs
does not automatically write the newline, by the way. But it's still better than fprintf
in the case of literal strings.