如何最好地消除有关未使用变量的警告?

2023-04-11C/C++开发问题
44

本文介绍了如何最好地消除有关未使用变量的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个跨平台应用程序,在我的一些函数中,并非所有传递给函数的值都被利用.因此我收到 GCC 的警告,告诉我有未使用的变量.

I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables.

围绕警告编码的最佳方式是什么?

What would be the best way of coding around the warning?

函数周围的#ifdef?

An #ifdef around the function?

#ifdef _MSC_VER
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal qrLeft, qreal qrTop, qreal qrWidth, qreal qrHeight)
#else
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal /*qrLeft*/, qreal /*qrTop*/, qreal /*qrWidth*/, qreal /*qrHeight*/)
#endif
{

这太难看了,但似乎是编译器喜欢的方式.

This is so ugly but seems like the way the compiler would prefer.

或者我是否在函数末尾为变量赋值为零?(我讨厌它,因为它改变了程序流程中的某些内容以消除编译器警告).

Or do I assign zero to the variable at the end of the function? (which I hate because it's altering something in the program flow to silence a compiler warning).

有正确的方法吗?

推荐答案

您可以将它放在 "(void)var;" 表达式(什么都不做)中,以便编译器看到它被使用.这在编译器之间是可移植的.

You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.

例如

void foo(int param1, int param2)
{
    (void)param2;
    bar(param1);
}

或者,

#define UNUSED(expr) do { (void)(expr); } while (0)
...

void foo(int param1, int param2)
{
    UNUSED(param2);
    bar(param1);
}

这篇关于如何最好地消除有关未使用变量的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6