why( warning: left-hand operand of comma expression has no effect)

Sam Bobroff sbobroff at shoretel.com
Tue Nov 20 02:16:04 CET 2012


On 16/11/12 23:09, Yoran Heling wrote:
[snip]
> Just look at the source:
>
>    assert (("libev: watcher has invalid priority", ABSPRI (w) >= 0 && ABSPRI (w) < NUMPRI));
>
> The string has absolutely no effect to the behaviour of the code, so the
> warning makes sense. However, that string *is* quite useful if the
> assertion fails: That string will be included in the output, so you'll
> (hopefully) know what went wrong without going through the source.
[snip]

I think the story is a little more complicated:
* assert(), from assert.h, takes ONE argument, not two. That's why there
are two parenthesis around the arguments: they aren't two arguments,
they are a single "comma statement".
* assert() is not a function, it's a macro.

The string DOES get printed if the assert triggers, but not because it's
a string that's passed in as an argument: it's because the assert macro
"stringifys" it's argument. Normally this would cause the "test
expression" (the argument to assert) to be printed, e.g.:

assert(x == 1)

would print:

"Assertion 'x == 1' failed."

But because C allows you to string several statements together using
comma (and it's value is the last statement), we can hack some extra
information into it:

assert(("bad mojo", x == 1))

Causes this to be printed:

"Assertion '("bad mojo", x == 1) failed."

The assert() call is still just testing that x == 1, the "bad mojo" term
is discarded by the compiler (in the test code), which causes the
warning, but it's been stringified into another argument in the macro,
so we get to see it. A nice hack maybe, but a hack nonetheless ;-)

So the compiler is almost correct: the string term is discarded and does
nothing... however it's failed to see is that it's been stringified and
THAT does something. Really, this is more of a bug in either assert.h or
gcc (IMHO)... but you could also call it "just a side effect of the hack".

Maybe those hack strings should removed from the assert calls and be
moved into comments in the code?

Sam.
>
> Yoran.
>
> _______________________________________________
> libev mailing list
> libev at lists.schmorp.de
> http://lists.schmorp.de/cgi-bin/mailman/listinfo/libev

________________________________

This e-mail and any attachments are confidential. If it is not intended for you, please notify the sender, and please erase and ignore the contents.



More information about the libev mailing list