我试着SQR在下面的代码中使用宏的定义:
#define SQR(x) (x*x)
int main()
{
int a, b=3;
a = SQR(b+5); // Ideally should be replaced with (3+5*5+3), though not sure.
printf("%d\n",a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它打印23.如果我将宏定义更改为SQR(x) ((x)*(x))然后输出是预期的,64.我知道在C中调用宏会用宏的定义替换调用,但是我仍然无法理解它是如何计算的23.
我想使用C99中定义的复数,但我需要支持不支持它的编译器(MS编译器会浮现在脑海中).
我不需要很多功能,并且在没有支持的情况下在编译器上实现所需的功能并不困难.但我很难实现'类型'本身.理想情况下,我想做的事情如下:
#ifndef HAVE_CREAL
double creal(complex z)
{
/* .... */
}
#endif
#ifndef HAVE_CREALF
float creal(float complex z)
{
/* ... */
}
#endif
Run Code Online (Sandbox Code Playgroud)
但是如果编译器无法识别'float complex',我不确定如何做到这一点.我实际上认为这是不可能的,但Dinkumware的C库似乎表明不是这样.解决办法是什么 ?我不介意使用函数/宏来对类型进行操作,但我需要一种方法来为复数赋值,并以与C99兼容的方式返回其实/虚部分.
我最终做了这样的事情:
#ifdef USE_C99_COMPLEX
#include <complex.h>
typedef complex my_complex;
#else
typedef struct {
double x, y;
} my_complex;
#endif
/*
* Those unions are used to convert a pointer of my_complex to native C99
* complex or our own complex type indenpendently on whether C99 complex
* support is available …Run Code Online (Sandbox Code Playgroud)