宏定义中的括号错误 [英] Bad parentheses in macro definition

查看:101
本文介绍了宏定义中的括号错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读斯坦福的教程,他们说:

I was reading this tutorial of stanford where they say :

常见的编码错误:

宏定义中的括号括起来

#define min(a, b) a<b?a:b // incorrect
#define min(a, b) (((a)<(b))?(a):(b)) // correct

我什至在程序中运行了它,效果很好.

I even ran this in a program, It worked fine.

谁能解释一下他们想说什么!

Can anybody explain what they are trying to say!

推荐答案

如果将其与其他运算符结合使用,则第一个版本将失败:

The first version fails if you combine it with other operators:

min(a , b) + c 

并翻译为:

a<b?a:b+c 

与以下内容相同:

a<b?a:(b+c) 

考虑到括号,这是一个意外的结果.

which is an unexpected outcome given the starting parenthesis.

第二个版本不是更好.如果将函数或 i ++ 传递给宏,它将两次评估其中一个参数,这可能导致意外行为.

The second version isn't much better. It evaluates one of the parameters twice which can cause unexpected behavior if a function or i++ is passed to the macro.

应该使用内联函数代替那些宏.

An inline function should be used instead of those macros.

这篇关于宏定义中的括号错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆