C代码宏,怪异的财产以后 [英] C macro, somthing weird

查看:128
本文介绍了C代码宏,怪异的财产以后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出东西在C近拍简单,
这code,例如:

trying to figure out something simple in C Macro, this code for example:

#include <stdio.h> 
#define MACRO(b)  printf("%d\n", b*b)

int main()
{
    MACRO(4+1); 
}

这code是9的输出,我认为它应该是25,
我没有任何想法,为什么,以及如何对这样的结果是9,而不是25。

The output for this code is 9, I think that it should be 25, I don't have any idea why and how the result for this is 9 and not 25.

推荐答案

在使用宏时,preprocessor替换它和它的参数相当逐字,所以在你的code宏扩展看起来像

When you use the macro, the preprocessor replaces it and its arguments quite verbatim, so the macro expansion in your code will look like

printf("%d\n", 4+1*4.1);

这不会为你提供你想要的结果,这是该函数宏被人瞧不起的原因之一。

That will not provide you with the result you want, and it is one of the reasons that function-like macros are looked down upon.

您需要使用括号,以确保不会发生这样的问题:

You need to use parentheses to make sure this problem doesn't occur:

#define MACRO(b)  printf("%d\n", (b)*(b))

然后边将导致如下扩展

while will then result in the following expansion:

printf("%d\n", (4+1)*(4.1));

每当你有相关的东西preprocessor的问题,也有几乎所有的编译器停止preprocessing阶段之后的选择,它可以让你看preprocessed来源,这将帮助你像这样的问题。

Whenever you have problems with something preprocessor related, there are options for just about all compilers to stop after the preprocessing stage, which allows you to look at the preprocessed source and which will help you with problems like this.

另外请注意,另一个的可能这里的问题是,如果你传递作为参数传递给宏恩pression是如使用圆括号时,与一些副作用,即函数将被调用两次,副作用函数调用将发生两次,甚至

Also note that another possible problem here is if the expression you pass as argument to the macro is e.g. a function call with some side-effect that function will be called twice and the side-effect will be happen twice, even when using parentheses.

有一个简单的例子,使用宏:

A simple example, using your macro:

int my_function(void)
{
    printf("Foo\n");
    return 1;
}

int main(void)
{
    MACRO(my_function());
}

以上程序将打印富\\ N两次的。如果 MACRO 是一个正确的函数调用 my_function 只会发生一次,并从功能,打印输出只会发生一次

The above program will print "Foo\n" twice. If MACRO was a proper function the call to my_function would only happen once and the printout from the function would only happen once.

这篇关于C代码宏,怪异的财产以后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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