Suppress unused variable warning in C++ => Compiler bug or code bug?

后端 未结 5 1087
無奈伤痛
無奈伤痛 2021-01-04 10:04

Presently, I am using the following function template to suppress unused variable warnings:

template
void
unused(T const &) {
  /* Do n         


        
5条回答
  •  时光说笑
    2021-01-04 11:04

    The answer proposed by haavee (amended by ur) is the one I would normally use:

    int f(int a, float /*epsilon*/) {
         return a*2;
    }
    

    The real problem happens when the argument is sometimes but not always used in the method, e.g.:

    int f(int a, float epsilon) {
    #ifdef LOGGING_ENABLED
         LOG("f: a = %d, epsilon = %f\n", a, epsilon);
    #endif
         return a*2;
    }
    

    Now, I can't comment out the parameter name epsilon because that will break my logging build (I don't want to insert another #ifdef in the argument list because that makes the code much harder to read).

    So I think the best solution would be to use Tom's suggestion:

    int f(int a, float epsilon) {
    (void) epsilon;    // suppress compiler warning for possibly unused arg
    #ifdef LOGGING_ENABLED
         LOG("f: a = %d, epsilon = %f\n", a, epsilon);
    #endif
         return a*2;
    }
    

    My only worry would be that some compilers might warn about the "(void) epsilon;" statement, e.g. "statement has no effect" warning or some such - I guess I'll just have to test on all the compilers I'm likely to use...

提交回复
热议问题