5

I'm writing a templated function* similar to the following:

template <typename T, bool v> 
void foo(T t1) {
    /* common code */
    if (v) {
        int i = bar();
        /* ... */
        return;
    }
    else {
        /* ... */
    }
    /* more common code */
}

When I compile this and foo is instantiated with v set to false, the compiler says:

warning: dynamic initialization in unreachable code

Now, the code is unreachable because of the template argument; and this should be perfectly acceptable. How can I avoid or suppress this warning? I would rather not suppress such warnings altogether.

Notes:

  • I would rather not specialize differently for true and false, since there's some common code, and I don't want to duplicate, nor artificially create another function.
  • Actually it's a CUDA kernel being compile by NVCC. If you can answer the question more generally, please do, otherwise answer specifically for this case.
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • You could specialize for `v`. – RedX Mar 27 '14 at 10:13
  • 1
    I fear, your test case does not reflect the actual problem –  Mar 27 '14 at 10:13
  • @pmr this is true, but I have often seen code like this in CUDA code. This way, the device code can be optimized better, leading to less code and often smaller register usage in comparison to using a function parameter, while still avoiding duplicate code. – anderas Mar 27 '14 at 10:36
  • @pmr: Edited my example so as to make your comment less of an issue, i.e. to make specialization less relevant. Also, I think nvcc would prevent a partial specialization on `v` only. – einpoklum Mar 27 '14 at 11:56

1 Answers1

4

With the current construction, there is no simple way of really fixing it that I'm aware of (I had the same problem, also with NVCC). However, you can specialize the template for v=true and only insert the code inside the if(v)-statement only in that specialization.

This is by no means an optimal solution since it can lead to code duplication, but will fix the warning.

If you are using GCC as the host compiler and the error is in host code, you could also try suppressing the warning like this:

#pragma GCC diagnostic ignored "-Wunreachable-code"

edit: just noticed that this is probably the wrong warning code since it is about dead code in general. The full list of warnings can be found here: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

This question might also be of interest: How to disable compiler warnings with nvcc

Community
  • 1
  • 1
anderas
  • 5,744
  • 30
  • 49
  • What's the scope of this pragma? How do I turn it off? Also, I tweaked my example so as to make it even less reasonable to specialize for v=true. – einpoklum Mar 27 '14 at 11:58
  • 1
    The scope is "until the end of the compilation unit". To save/restore the current state, use `#pragma GCC diagnostic push` and `#pragma GCC diagnostic pop`, respectively. – anderas Mar 27 '14 at 12:00