Выражение заявления Марка, как может быть неиспользованными


March 2019


148 раз


Как отмечает выражение заявления , т.е.

({struct Value * t = expr; set(t,val); t;})

а может быть неиспользованными, т.е.


Это автоматически сгенерированный код, с побочными эффектами. Выведение ли результат не используется и замены в (void)0течение tпо времени генерации приведет к значительному увеличению сложности. Опрятное решение было бы пометить его как может быть неиспользованными, то я должен буду делать -Wno-unused-value.


2 ответы


Yes, this can be quite disturbing if you use such things in macros or alike. I usually silence such warnings by using a completely useless assignment at the end:

t = t;

This has two effects: the compiler now thinks that t is used, and also that the result of that is an rvalue so nobody can try to take the address of the whole ({ }) expression.


Here's what I use:

// tell compiler to shut up about unused variables
#define VARIABLE_USED(_sym) \

__attribute__((__always_inline__)) static inline
_variable_used(int flg)
  • You may need variants based on your actual types. But, because of the !! trick, the above works for almost any intrinsic type (inc. pointers)
  • You may need inline instead of static inline depending on your compiler
  • Without __attribute__((__always_inline__)) if your compiler complains about it

So, somewhere in the code just add VARIABLE_USED(my_unused_variable); for all your unused symbols.

NOTE: This is zero overhead (i.e. generates no extra code). It may seem like it does with the formulation of the argument, but because of the inline definition, it gets optimized away. But, it does trick the compiler into thinking the variable has been used.

The above is what I've used for a long time. But, I just thought up a possibly simpler variant [this is untested]:

// tell compiler to shut up about unused variables
#define VARIABLE_USED(_sym) \
    do { \
        if (1) \
        if (!! _sym) \
            break; \
    } while (0)

These macros might work for a struct, as is:

struct foobar foo;