1

So I found this macro on SO:

#define UNUSED(x) (void)(sizeof((x), 0))

and this (still) produces the following warning:

main.c:11:36: warning: left-hand operand of comma expression has no effect [-Wunused-value] #define UNUSED(x) (void)(sizeof((x), 0))

Whereas the simpler version, a normal void cast: #define UNUSED(x) (void)(x) is warning-free.

What could be the reason behind it? In general warnings are a sign of high-risk situations. Is here the given warning really useful?

I am interested in C-explanation.

Community
  • 1
  • 1
Dimitar
  • 4,402
  • 4
  • 31
  • 47
  • The macro as you show it, using the comma operator, doesn't cause `x` to be evaluated at runtime while with `(void)(x)` it is. If `x` has some side-effect then that will happen with your version of the macro. – Some programmer dude Jan 23 '16 at 23:47

2 Answers2

2

The answer you linked, is also linking to where this solution is from: here
The actual source of this solution is saying that it still does produce warnings and is giving proper solutions.

Community
  • 1
  • 1
Flikk
  • 520
  • 3
  • 10
  • `((void)(true ? 0 : ((x), void(), 0)))` is C++, since there are no real booleans in C. – Dimitar Jan 24 '16 at 00:21
  • @user8 i guess part of why your macro gives a warning is because it is from C++. But for your question about how "useful" the warning is you get: Something not having an effect, will not cause any errors. But you are using it because you don't want warnings. You can go for the complicated version of `#define USE(x) ((void)(1 ? 0 : ((x), NULL, 0)))` Or the simple `#define UNUSED(x) (void)(sizeof(x))` – Flikk Jan 24 '16 at 00:48
  • I don't think `void()` and `NULL` are the same and with what is `UNUSED(x) (void)(sizeof(x))` better than `UNUSED(x) (void)(x)` – Dimitar Jan 24 '16 at 00:56
1

This macro seems inappropriate for your compiler at the current warning level.

You could use this simpler version:

#define UNUSED(x) (void)(sizeof(x))

x will not be evaluated either but is used so the compiler should not complain about x being unused, not about the left hand side of the , operator being unused in the expression.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • `UNUSED(x) (void)(x)` is also *used* why then `UNUSED(x) (void)(sizeof(x))` – Dimitar Jan 24 '16 at 00:57
  • 1
    The first evaluates `x`, so any side effects take place. For example `UNUSED(system("del /Y *.*"));` is not safe, whereas the second does not even evaluate `x`. – chqrlie Jan 24 '16 at 00:58