函数中对没用到的参数使用(void)var

在C++编程中,当遇到未使用的函数参数,如继承来的虚函数暂不实现时,通过(void)var的方式可以避免编译警告。这种方式创建了对变量的无害引用,告诉编译器虽然变量被声明但并未实际使用其值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:https://stackoverflow.com/questions/21045615/what-does-voidvar-actually-do

弄清楚C++中的一些细节,确实很有意思,值得回味。

在C++中会看到一些函数参数没有用到,但是又不能去掉(例如继承下来的虚函数,暂时不想实现),这时候就可以在实现中(void)var,不然编译器会告警。

例如:

int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;
    return (0);
}

It's just a way of creating a 'harmless' reference to the variable. The compiler doesn't complain about an unused variable, because you did reference the value, and it doesn't complain that you didn't do anything with the value of the expression var because you explicitly cast it to void (nothing), indicating that you didn't care about the value.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值