c++ - 在 if 语句中沉默 -Wunused-variable

标签 c++ warnings compiler-warnings suppress-warnings

以下代码生成一个警告,指出未使用 temp(这是真的):

#include <cstdio>

int f() { return 5; }

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

    return 0;
}

问题是我需要在不使用 gcc -Wall 和 clang -Weverything 生成警告的情况下执行此操作(我正在实现类似于 CatchSECTION() 内容的功能。

那么有什么方法可以让它静音呢?我尝试使用 __attribute__((unused))

全局使用 -Wno-unused-variable 对我来说不是一个选择,因为我正在编写一个仅 header 的库。

最佳答案

#include <cstdio>

int f() { return 5; }

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

  return 0;
}

这会消除 GCC 和 clang 的警告。

关于c++ - 在 if 语句中沉默 -Wunused-variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35570835/

相关文章:

c# - 为隐式转换启用编译器警告 (C#)

c - 警告 - 初始化使指针从整数而不进行强制转换

c# - 可空引用类型 : "Try" method pattern, 在返回 false 时收到 null 警告

c++ - 在 Matcher 中使用 gtest 浮点比较

c++ - 如何使用删除删除成语从结构 vector 中删除值?

php - 无法执行 PDO 查询(无效参数号)但不无效

cocoa - Cocoa 中不支持的配置错误 (Xcode)

bash - 解压缩 - 警告和 map 名称

c++ - windbg !analyze -v 输出中的 "BUGCHECK_STR: APPLICATION_FAULT_NULL_CLASS_PTR_READ_AFTER_CALL"是什么意思

c++ - 如果存在专门化,如何限制模板化函数?