C ++定义表达式求值 [英] C++ define expression evaluation

查看:123
本文介绍了C ++定义表达式求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有这个表达式:

  #define cube(x)x * x * x 

然后我们称之为:

  int n = 3,v; 
v = cube(n + 1); // v = 10
v = cube((n + 1)); // v = 64
v = cube(n); // v = 27

所以问题是:为什么第一个操作不会使 v = 64

解决方案

宏不进行评估



在编译文件之前,还有一个名为 C预处理器以文字方式替换宏调用 / 并准备

  #define cube(x)x * x * x当你这样做

  v = cube(n + 1); 

替换为此( expaned是正确的字词

  v = n + 1 * n + 1 * n + 1; 
//简化为
v = n + n + n + 1;
//和
v = 3 * n + 1;

n = 3 code> 10 正确的观察结果。



注意,当你添加括号

  v = cube((n + 1)); 

然后,扩展名为

  v =(n + 1)*(n + 1)*(n + 1) 

这是你期望的 cube()

  #define cube(x)((x)*如果使用 gcc ,请尝试   / p> 

  gcc -E source.c 

并检查结果以验证宏是如何扩展的。


Suppose we have this expression:

#define cube(x) x * x * x

And then we call it:

int n = 3, v;
v = cube(n + 1);   // v = 10
v = cube((n + 1)); // v = 64
v = cube(n);       // v = 27

So the question is: why first operation do not make v = 64?

解决方案

Macros are not evaluated (in the sense of the common interpretation of evaluation), they are expanded at compile time.

Before the file is compiled, there is another program called the C Preprocessor that replaces the macro invocation literally/textually and prepares the file for actual compilation, so for your macro

#define cube(x) x * x * x when you do this

This

v = cube(n + 1);

is replaced with this (expaned is the correct term)

v = n + 1 * n + 1 * n + 1;
// Simplifies to
v = n + n + n + 1;
// and again
v = 3 * n + 1;

which for n = 3 gives you 10 exactly the observed result.

Note, that when you add parentheses

v = cube((n + 1));

then, the expansion is

v = (n + 1) * (n + 1) * (n + 1);

which is what you would expect cube() to do, so prevent this you should redefine your macro like this

#define cube(x) ((x) * (x) * (x))

If you are using gcc try

gcc -E source.c

and check the result to verify how the macro was expanded.

这篇关于C ++定义表达式求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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