Uses fflush (stdout) as an argument to fprintf () safe?

I came to this line of code:

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

Note that the message does not contain% -tag.

Is it safe in visual c ++? fflush () returns 0 on success and EOF on failure. What will fprintf () do with this extra parameter?

At first I thought it was a strange hack to add a call to fflush () without requiring an extra line. But it is written that the call to fflush () will be executed before the call to fprintf (), so that it does not clear the message that is being printed right now, but those that are waiting to be reddened if they are ... am I right?

+4
source share
3 answers

It is safe. Here that C (C99 atleast, paragraph 7.19.6.1) says this

If the format is exhausted, the arguments remain, redundant arguments must be evaluated, but otherwise ignored.

If the goal was to avoid the line, I would rather do

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

if nothing more than to prevent the person who later reads this code to track me down with the bat.

+4
source

fprintf does not know the exact number of parameters, it tries to load only one argument for "%". If you provide fewer arguments than "%", this leads to undefined behavior; if you provide more arguments, they are ignored.

The second question in the question is, yes, this will only clear the messages in the queue, the new message will not be cleared.

0
source

I think fprintf uses varargs to handle the parameters, so any additional parameters should be safely ignored (and not that this is good practice or something else). And you're right that fflush will be called before fprintf, so this is a kind of pointless hack.

If there are enough warning flags (e.g. -Wall for gcc) you will get a warning

0
source

Source: https://habr.com/ru/post/1336333/


All Articles