为什么要使用只返回常量的函数而不直接使用常量?

4
我发现了GitHub上的一些代码。 https://github.com/codeplea/tinyexpr/blob/master/tinyexpr.c 以下这几行引起了我的注意:
static double pi(void) {return 3.14159265358979323846;}
static double e(void) {return 2.71828182845904523536;}

在这种情况下使用函数有什么理由吗?为什么不使用常量?你可以使用预处理器宏,但这可能会使调试变得更加困难。我以前从未见过这种用法。这样做有什么好处吗?

1个回答

8

我能想到的主要原因是使搜索使用该常量的位置更容易。例如,您可以搜索 e( 而不是 e

然而,在这里不是这种情况。这些函数确实被使用,但不是显式调用。

链接的代码包含一个结构体数组:

typedef struct te_variable {
    const char *name;
    const void *address;
    int type;
    void *context;
} te_variable;

...

static const te_variable functions[] = {
    /* must be in alphabetical order */
    {"abs", fabs,     TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"acos", acos,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"asin", asin,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"atan", atan,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"atan2", atan2,  TE_FUNCTION2 | TE_FLAG_PURE, 0},
    {"ceil", ceil,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"cos", cos,      TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"cosh", cosh,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"e", e,          TE_FUNCTION0 | TE_FLAG_PURE, 0},
    {"exp", exp,      TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"fac", fac,      TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"floor", floor,  TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"ln", log,       TE_FUNCTION1 | TE_FLAG_PURE, 0},
#ifdef TE_NAT_LOG
    {"log", log,      TE_FUNCTION1 | TE_FLAG_PURE, 0},
#else
    {"log", log10,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
#endif
    {"log10", log10,  TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"ncr", ncr,      TE_FUNCTION2 | TE_FLAG_PURE, 0},
    {"npr", npr,      TE_FUNCTION2 | TE_FLAG_PURE, 0},
    {"pi", pi,        TE_FUNCTION0 | TE_FLAG_PURE, 0},
    {"pow", pow,      TE_FUNCTION2 | TE_FLAG_PURE, 0},
    {"sin", sin,      TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"sinh", sinh,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"sqrt", sqrt,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"tan", tan,      TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {"tanh", tanh,    TE_FUNCTION1 | TE_FLAG_PURE, 0},
    {0, 0, 0, 0}
};

每个结构体的第二个成员都是一个函数指针,用于运行与数学相关的一些函数,E和PI的值也在其中。因此,它们被定义为函数以符合这个框架。

2
那个搜索方面实际上相当聪明。 - klutt
不是那么聪明。在搜索 e 时最好启用“仅限整个单词”,而不是使用 e(。或者在正则表达式搜索中使用 \be\b - phuclv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接