Home Ask Login Register

Developers Planet

Your answer is one click away!

user3482407 February 2016

Void wrapped function in journalctl source

I was recently browsing through the source code of journalctl and found a piece of code that was not really clear to me.

The part I am talking about is right here: https://github.com/systemd/systemd/blob/9e83569d8ff219730912ecac441843b9531b079c/src/shared/logs-show.c#L1056

Seems like they want to avaoid multiple checks like this

r = sd_journal_add_match(...);
if (r < 0) {
    //some error

by || the outputs together.

Wouldn't that also be possible by doing something like this:

r = sd_journal_add_match(...);
r |= sd_journal_add_match(...);

Why wrap the output in

(void) ( ... );


Thx in advance.


kwarnke February 2016


r |= sd_journal_add_match(...);

is not the same as

(r = sd_journal_add_match(j, "_UID=0", 0)) ||
(r = sd_journal_add_match(j, m2, 0)) ||

The |= operator is a bit-wise or operator together with assignment (same as r = r | sd_()), where || is the logical or operator. All sd_jourcal_ function are executed until one of them returns a non-zero value. Then r contains these non-zero value. This is called short-circuitevaluation.

Second, I guess it is the same reason why we (should) cast the return value of a function to void if you are not interested in to use them. For example:

(void)printf("Hello World");

This communicates that you now that printf() returns a value, but you are not check them. Usually you should check always the return value:

if (printf("Hello World") < 0) {
    // do some error handling here

Simply writing

printf("Hello World");

ignores the return value silently, which is a bad idea. I guess, there are tools out there (like lint) for critical software, which can check this.

For the example you provided, the result of the || chain is casted to void. Without the cast, the code looks strange, because there is a value calculated, but not assigned. Similar like this

f() || g(); // better (void)(f() || g());

Post Status

Asked in February 2016
Viewed 1,528 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life