简体   繁体   English

什么是“(void)指针;”在c ++中是什么意思?

[英]What does “(void)pointer;” mean in c++?

There are some c++ code 有一些c ++代码

struct data {
    /* some fields */
};

typedef struct data * pData;

int function(pData pointer) {
    if(pointer == NULL)
        return ERROR;
    (void)pointer;
    /* other work */
}

What does "(void)pointer" mean? “(void)指针”是什么意思?

Just for your information, there are some int/char*/etc, some functions pointers which are used as callback functions in the structure. 仅供参考,有一些int / char * / etc,一些函数指针在结构中用作回调函数。

It is used to circumvent an unused-variable warning. 它用于规避未使用的变量警告。

If you do use the variable, it is a no-op. 如果你确实使用了这个变量,那就是无操作。

Mostly unused variables are parameters, that are required to fulfil a signature for a callback function, but not needed in your actual implementation. 大多数未使用的变量是参数,它们是实现回调函数签名所必需的,但在实际实现中不需要。

Cf. 参看

Update: 更新:

Just because it was not mentioned otherwise: The type of the variable might be anything. 仅仅因为没有提到它:变量的类型可能是任何东西。 It is not constricted to pointer types. 它不受指针类型的限制。

It doesn't mean a whole lot. 这并不意味着很多。

It evaluates the expression pointer , then explicitly ignores it by casting it to void . 它计算表达式pointer ,然后通过将其转换为void显式忽略它。

Sometimes you see this construct when trying to convince a compiler not to warn for an un-used argument, but in your code the argument is already used since it's being NULL -checked. 有时,当您试图说服编译器不要警告未使用的参数时,您会看到此构造,但在您的代码中,该参数已被使用,因为它已被NULL检查。

It casts the pointer value to a "no type" value, or that it is "absent of a type". 它将指针值转换为“无类型”值,或者“没有类型”。

void foo(); // absent of a return value 
int bar(void); // absent of parameters
void *var; // Type of the variable pointed to is absent
(void) var; // The type of the variable is absent

It is a typical way to suppress unused variable compiler warning. 这是一种抑制未使用的变量编译器警告的典型方法。

However, since the pointer is actually used as if(pointer == NULL) , I see no reason do that. 但是,由于指针实际上被用作if(pointer == NULL) ,我认为没有理由这样做。

If I have to guess, I would guess that the NULL check and return is added later than the warning suppression. 如果我不得不猜测,我猜想NULL检查和返回是在警告抑制之后添加的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM