Search code examples
c++warningscompiler-warningssuppress-warnings

Silencing -Wunused-variable in an if statement


The following code generates a warning that temp is not used (which is true):

#include <cstdio>

int f() { return 5; }

int main() {
    if(const int& temp = f()) {
        printf("hello!\n");
    }

    return 0;
}

The thing is that I NEED to do this without generating a warning with gcc -Wall and clang -Weverything (I'm implementing a feature similar to the SECTION() stuff of Catch) .

So any ways to silence it? I tried using __attribute__((unused)).

Using -Wno-unused-variable globally is not an option for me since I'm writing a header only library.


Solution

  • #include <cstdio>
    
    int f() { return 5; }
    
    int main()
    {
      if (const int &temp __attribute__((unused)) = f()) {
        printf("hello!\n");
      }
    
      return 0;
    }
    

    This silences the warning for GCC and clang.