gpt4 book ai didi

c - "int j = (strlen) (str)"是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 15:45:50 31 4
gpt4 key购买 nike

我从 bstrlib 中找到了以下代码,在 bstrlib.c 中(例如第 193 行):

bstring bfromcstr (const char * str) {
bstring b;
int i;
size_t j;

if (str == NULL) return NULL;
j = (strlen) (str);
i = snapUpSize ((int) (j + (2 - (j != 0))));
if (i <= (int) j) return NULL;

b = (bstring) bstr__alloc (sizeof (struct tagbstring));
if (NULL == b) return NULL;
b->slen = (int) j;
if (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) {
bstr__free (b);
return NULL;
}

bstr__memcpy (b->data, str, j+1);
return b;
}

(strlen) (str) 是什么意思?这种使用strlen的代码在bstrlib.c中很常见。

我在 OSX 机器上做了一些测试代码,但我无法理解也无法解释它的含义。

最佳答案

j = (strlen) (str);本质上与 j = strlen(str); 相同.

按照他们的方式编写代码将确保真实 strlen函数(来自 <string.h> )将被使用,即使它被 function-like macro 隐藏名为 strlen() .

A function-like macro is only expanded if its name appears with a pair of parentheses after it. If you write just the name, it is left alone. This can be useful when you have a function and a macro of the same name, and you wish to use the function sometimes.

因为在 (strlen) (str) , strlen后面没有一对括号,宏不会展开。

这个例子应该展示:

#include <stdio.h>
#include <string.h>

/**
* Only check something like this in if you're
* planning on changing jobs very soon!
*/
#define strlen(s) 666

int main(void)
{
const char *str = "Stack Overflow";
size_t j;

/* This always uses the *real* strlen */
j = (strlen) (str);
fprintf(stderr, "(strlen) (str) = %zu\n", j);

/* This might be using a function-like macro */
j = strlen(str);
fprintf(stderr, "strlen(str) = %zu\n", j);

return 0;
}

输出:

$ ./a.out 
(strlen) (str) = 14
strlen(str) = 666

当然,下面的方法也行得通:

#include ...
...

#ifdef strlen
#undef strlen
#endif

关于c - "int j = (strlen) (str)"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068827/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com