Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid the "dynamic initialization in unreachable code" warning?

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.
like image 343
einpoklum Avatar asked Oct 01 '22 05:10

einpoklum


1 Answers

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

like image 158
anderas Avatar answered Oct 13 '22 10:10

anderas