用作简单函数的宏
Macros used as simple functions
Hi, I tried to define something comparable to a little function, even though it doesn't output any error the result is: 0.00000000
#include <stdio.h>
#define LOGIC(X,Y){\
if(X>Y)\
printf("%lf",X);\
else\
printf("%lf",Y);\
}
int main(){
LOGIC(4,3);
return 0;
}
Why is so and how to make it work?
首先,您应该有充分的理由选择类似宏的函数而不是实际函数。如果你使用过函数,你可以更自然地指定函数参数应该是double
。
void logic (double x, double y) {
if (x > y) {
printf("%lf\n", x);
} else {
printf("%lf\n", y);
}
}
由于您使用的是宏,因此没有为参数指定类型。因此,如果您将 int
参数传递给宏,这就是它在扩展中的处理方式。当 printf
被告知期望 double
参数而传入 int
时,会导致未定义的行为。
修复宏的一种方法是将参数分配给具有适当类型的局部变量,这样可以更好地模拟实际函数的作用。
#define LOGIC(X,Y) do {\
double XX = (X); \
double YY = (Y); \
if(XX>YY)\
printf("%lf",XX);\
else\
printf("%lf",YY);\
} while (0)
Hi, I tried to define something comparable to a little function, even though it doesn't output any error the result is: 0.00000000
#include <stdio.h>
#define LOGIC(X,Y){\
if(X>Y)\
printf("%lf",X);\
else\
printf("%lf",Y);\
}
int main(){
LOGIC(4,3);
return 0;
}
Why is so and how to make it work?
首先,您应该有充分的理由选择类似宏的函数而不是实际函数。如果你使用过函数,你可以更自然地指定函数参数应该是double
。
void logic (double x, double y) {
if (x > y) {
printf("%lf\n", x);
} else {
printf("%lf\n", y);
}
}
由于您使用的是宏,因此没有为参数指定类型。因此,如果您将 int
参数传递给宏,这就是它在扩展中的处理方式。当 printf
被告知期望 double
参数而传入 int
时,会导致未定义的行为。
修复宏的一种方法是将参数分配给具有适当类型的局部变量,这样可以更好地模拟实际函数的作用。
#define LOGIC(X,Y) do {\
double XX = (X); \
double YY = (Y); \
if(XX>YY)\
printf("%lf",XX);\
else\
printf("%lf",YY);\
} while (0)