函数式宏和奇怪的行为 [英] Function-like macros and strange behavior

查看:171
本文介绍了函数式宏和奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读Effective C ++,在第2项中的某一点,提到以下内容:

I have started reading Effective C++ and at some point in item 2, the following is mentioned:

// call f with the maximum of a and b
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))

...

int a = 5, b = 0;
CALL_WITH_MAX(++a, b); // a is incremented twice
CALL_WITH_MAX(++a, b+10); // a is incremented once




在调用f $ b之前递增b $ b取决于与什么进行比较!

Here, the number of times that a is incremented before calling f depends on what it is being compared with!

的确,如果我使用一个简单的打印语句在 f ,7在第一次调用打印,但我不能为我的生活找出为什么。我缺少明显的东西吗?

Indeed, if I use a simple print statement in f, 7 gets printed in the first call, but I cannot for the life of me figure out why. Am I missing something obvious?

推荐答案

编译器用逐字逐句替换宏的内容。所以你最终得到

The compiler replaces the macros with exactly what you pass in, verbatim. So you end up with

int a = 5, b = 0;
f((++a) > (b) ? (++a) : (b));
f((++a) > (b+10) ? (++a) : (b+10));

这篇关于函数式宏和奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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