assert , ASSERT中的void

本文探讨了C/C++语言中的assert宏及其在MFC中的实现ASSERT,强调了这两个宏在调试状态下的作用。void类型的使用旨在确保表达式无副作用,并遵循了void类型在C++中的规定和限制。

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

 

assert   

        C\C++语言提供的断言宏.

定义如下:

         #define assert(_Expression) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Expression), _CRT_WIDE(__FILE__), __LINE__), 0) )

ASSERT

        MFC提供的断言宏

定义如下:

       #define ASSERT(f)          DEBUG_ONLY((void) ((f) || !::AfxAssertFailedLine(THIS_FILE, __LINE__) || (AfxDebugBreak(), 0)))


今天有同事问道为什么在表达式的前面都有一个void.我想可能和ASSERT宏的使用场景有关吧. ASSERT/assert只在调试状态下才起作用,也就是说ASSERT/assert中的expression最好不能有side affect.如此表达式,自然不能随便做为子表达式,插入其他表达式中.想来,表达式类型强制转换成为void就是防止 ASSERT/assert 宏成为子表达式的吧.


翻了翻标准,重新了解了一下 void 的定义和约束:

The void type has an empty set of values.  The void type is an incomplete type that cannot be completed.
It is used as the return type for functions that do not return a value.  Any expression can be explicitly con-
verted to type cv void (5.4).  An expression of type void shall be used only as an expression statement
(6.2), as an operand of a comma expression (5.18), as a second or third operand of ?:(5.16), as the operand
of typeid, or as the expression in a return statement (6.6.3) for a function with the return type void.


任何表达式均可以显式转换成为 cv void [一直没有理解清楚,暂时理解成为void].  而 void 类型的表达式只可以用在在 表达式语句,逗号表达式,条件表达式,typeid以及返回值为void的函数的return中.这样转换没有完全达到目的,但是利用类型检查,已经可以应付大部分场景.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值