带消息的断言()
我看到某处断言以以下方式与消息一起使用:
assert(("message", condition));
这似乎工作得很好,除了 gcc 抛出以下警告:
warning: left-hand operand of comma expression has no effect
如何停止警告?
I saw somewhere assert used with a message in the following way:
assert(("message", condition));
This seems to work great, except that gcc throws the following warning:
warning: left-hand operand of comma expression has no effect
How can I stop the warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
使用
-Wno-unused-value
停止警告; (选项-Wall
包括-Wunused-value
)。我认为更好的是使用另一种方法,比如
Use
-Wno-unused-value
to stop the warning; (the option-Wall
includes-Wunused-value
).I think even better is to use another method, like
Try:
这样使用:
仅当断言失败时才会执行该块。
Try:
use as such:
Will execute the block only when assert fails.
如果要传递格式化消息,可以使用以下宏:
然后像 printf 一样使用它:
输出:
基于http://c.learncodethehardway.org/book/ex20.html
If you want to pass a formatted message, you could use the following macros:
Then use it like printf:
Output:
Based on http://c.learncodethehardway.org/book/ex20.html
按照传统,
(void)
会向编译器传达您故意忽略表达式的信息:By tradition,
(void)
communicates to the compiler that you are knowingly ignoring an expression:我喜欢在 C 中这样做。这允许通过以下方式调用
assert
:以下是代码:
I like to do it this way in C. This allows calling
assert
the following ways:Here is the code:
对于意外的开关默认情况,选项是
For unexpected default case of a switch, an options is
接受 const char* 并返回 true 的函数可能会让您免受各种警告:
A function that takes
const char*
and returnstrue
would probably save you from all sorts of warnings:就我而言,我更改了 @pmg 的答案以便能够控制输出。
(... && "message")
对我不起作用。In my case, I changed @pmg's answer to be able to control the output. The
(... && "message")
didn't work for me.您可以编写自己的宏来提供与
_Static_assert(expr, msg)
相同的用法:我还有一个宏
warn_bug()
来打印程序的名称,文件、行、函数、errno 值和字符串以及用户消息,即使断言已禁用。其背后的原因是它不会破坏程序,但会警告可能存在错误。不过,如果define(NDEBUG)
,您可以将assert_msg
定义为空。You could write your own macro that provides the same usage of
_Static_assert(expr, msg)
:I also have a macro
warn_bug()
that prints the name of the program, the file, the line, the function, the errno value and string, and a user message, even if asserts are disabled. The reason behind it is that it won't break the program, but it will warn that a bug will probably be present. You could just defineassert_msg
to be empty ifdefined(NDEBUG)
, though.根据以下链接
http://www.cplusplus.com/reference/clibrary/cassert/assert/
断言只需要表达式。可能您正在使用一些重载函数。
据此,只允许表达,因此您会收到此警告。
According to following link
http://www.cplusplus.com/reference/clibrary/cassert/assert/
assert is expecting only expression. May be you are using some overloaded function.
According to this, only expression is allowed and thus you are getting this warning.