Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 宏函数不需要的(或不稳定的)结果_C_Macros - Fatal编程技术网

C 宏函数不需要的(或不稳定的)结果

C 宏函数不需要的(或不稳定的)结果,c,macros,C,Macros,下面带有输入2、3、10的代码旨在给出12.5作为结果。([总和(2,3,10)(=15)+最大的(2,3,10)(=10)]/最小的(2,3,10)(=2)) 但结果是它输出了2000个,这是不需要的,也是错误的。我是在犯优先级错误还是在犯什么样的错误 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <ctype.h&

下面带有输入2、3、10的代码旨在给出12.5作为结果。([总和(2,3,10)(=15)+最大的(2,3,10)(=10)]/最小的(2,3,10)(=2)) 但结果是它输出了2000个,这是不需要的,也是错误的。我是在犯优先级错误还是在犯什么样的错误

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define MIN( a, b ) ( ( a < b ) ? (a) : (b) ) // Why are the parantheses imporant?
#define MAX( a, b ) ( ( a < b ) ? (b) : (a) )
#define LARGEST( a, b, c ) ( MAX( a, b ) < c ) ? c : ( MAX( a, b ) )
#define SMALLEST( a, b, c ) ( a < MIN( b, c ) ) ? a : ( MIN( b, c ) )
#define SUM( a, b, c ) ( (a + b + c) )
#define EXPR( a, b, c ) ( (LARGEST( a, b, c ) + SUM( a, b, c ) ) /  SMALLEST( a, b, c ) ) 

int main(){
    float a, b, c;
    printf("Enter three integers!\n");
    scanf(" %f", &a);
    scanf(" %f", &b);
    scanf(" %f", &c);
    printf("The result is %f.\n", EXPR(a, b, c));   
    return 0;
}
#包括
#包括
#包括
#包括
#包括
#定义MIN(a,b)((a
要查看预处理器生成的实际代码,只需执行此命令

gcc -E main.c 
我们将获得(最后一个命令输出的最后一部分)

因此,让我们调用刚才处理过的左块(就在上面)LeftBlock,以简化下一次分析

因此,结合
/
运算符的右操作数(或整个语句的左操作数),我们将得到

LeftBlock / ( a < ( ( b < c ) ? (b) : (c) ) ) ? a : ( ( ( b < c ) ? (b) : (c) ) )
正如您所看到的,缺少括号会导致不期望的结果

关于宏还有许多其他的陷阱,你应该避免。你可以从这里检查其中的一些


最后我想我解决了这个问题!!:)

> P.因为宏观扩张代替了宏观文本的每一个时间,例如考虑这个简单的宏

#define SQR(x) x * x
此宏在这样使用时

double x = SQR(1.0 + 2.0);
将扩展到

double x = 1.0 + 2.0 * 1.0 + 2.0;
double x = (1.0 + 2.0) * (1.0 + 2.0);
如果添加括号,它们也将被插入

#define SQR(x) (x) * (x)
然后它会扩展到

double x = 1.0 + 2.0 * 1.0 + 2.0;
double x = (1.0 + 2.0) * (1.0 + 2.0);

当我使用括号内的函数时,它产生了
9.0

#define EXPR(a,b,c)((最大的(a,b,c))+(总和(a,b,c))/(最小的(a,b,c)),它工作得很好。但是为什么括号很重要呢?请查看预处理器输出(运行
gcc-E yourfile.c | tail
或其他内容)以查看宏的扩展情况。请记住,宏扩展只是文本替换,嵌套宏不会按照函数调用的意义进行计算。用函数替换宏,代码将(神奇地)工作。这肯定是运算符
+
之间的优先级问题:
!!添加具有
最小值(a,b,c)
-->
((a
。与
最大()相同。
#define SQR(x) (x) * (x)
double x = (1.0 + 2.0) * (1.0 + 2.0);