开发者

Is using fflush(stdout) as fprintf() argument safe?

To I came upon this line of code:

fprintf(stdout, "message", fflush(stdout));

Note that the message does not contain any %-tag.

Is that safe in visual c++? ff开发者_开发技巧lush() returns 0 on success and EOF on failure. What will fprintf() do with this extra parameter?

I first thought that this was a strange hack to add a fflush() call without needing an extra line. But written like this, the fflush() call will be executed before the fprintf() call so it does not flush the message being printed right now but the ones waiting to be flushed, if any... am I right?


It's safe. Here's what C (C99 atleast, paragraph 7.19.6.1) says about it

If the format is exhausted while arguments remain, the excess arguments shall be evaluated but are otherwise ignored.

If the goal was to avoid a line, i'd rather do

fflush(stdout); fprintf(stdout, "message");

if for nothing else than to prevent the person later reading that code to hunt me down with a bat.


fprintf doesn't know the exact number of parameters, it only tries to load one argument per '%'. If you provide less arguments than '%', it results in undefined behavior, if you provide more arguments, they are ignored.

Ad second question, yes, this would only flush messages in queue, the new message won't be flushed.


I think fprintf is using varargs to process parameters, so any extra parameters should be safely ignored (not that it's a good practice or anything). And you are right that fflush will be called before fprintf, so this is kind of a pointless hack.

With enough warning flags enabled (like -Wall for gcc) you will get a warning

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜