C 用 typedef 限制

发布于 2024-10-01 19:23:20 字数 273 浏览 2 评论 0原文

我现在正在做一些代码,但使用restrict关键字遇到了一些问题。

typedef int* pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}

如果我想限制a和b怎么办?下面的代码失败了:

typedef int* pt;

int foo(pt restrict a, pt restrict b)
{
 ... /* stuff */
}

提前致谢。

i'm doing some code now and got some problem using restrict keyword.

typedef int* pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}

What if I want to make a and b restricted? The code below failed:

typedef int* pt;

int foo(pt restrict a, pt restrict b)
{
 ... /* stuff */
}

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你在看孤独的风景 2024-10-08 19:23:20

确保您使用编译器的 C99 标志来编译它。 C89 C 中不存在 restrict 关键字。

Make sure you're compiling it using the C99 flag for your compiler. The restrict keyword doesn't exist in C89 C.

眼泪也成诗 2024-10-08 19:23:20

快速浏览并阅读这个类似的SO问题,代码将是,如关键字“restrict”不是 C++ 编译器中的保留关键字,如上面链接中接受的答案所示,__restrict__restricted__,再次检查您的编译器...

typedef int* __restrict pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}

Having a quick look and reading this similar SO question, the code would be, as the keyword 'restrict' is not reserved keyword in C++ compilers, as indicated by the accepted answer in the above linky, either __restrict or __restricted__, again, check your compiler...

typedef int* __restrict pt;

int foo(pt a, pt b)
{
 ... /* stuff */
}
残龙傲雪 2024-10-08 19:23:20

您需要一个“指向整数的受限制指针”int * limit p,而不是“指向受限制整数的指针”restrict int *p,因此您需要创建另一个 typedef。你无法“触及”原来的东西。

编辑:虽然您确实无法到达 typedef 内部,并且修饰符将始终应用于顶层,但在这种情况下,事实证明您想要 < code>restrict 在顶层。这与人们通常遇到的 const 相反:typedef char *char_ptr 表示 const char_ptr (或 char_ptr const >,它们是等价的)都意味着“指向 char 的常量指针”而不是人们想要的“指向常量 char 的指针”。 请参阅此 SO 线程: C++ typedef 解释 const 指针

(另 在这种情况下,我认为 typedef int *pt 确实意味着 restrict pt 意味着 int *restrict pt。验证起来非常容易,因为 gcc 会抱怨 restrict int *x 的“'restrict' 无效使用”,但不会抱怨 restrict pt x 的“'restrict' 无效使用”。

You need a "restricted pointer to integer" int * restrict p not a "pointer to restricted integer" restrict int *p so you will need to make another typedef. You can't "reach inside" the original one.

EDIT: While it's true that you can't reach inside the typedef and the modifier will always apply at the top level, in this case it turns out that you want the restrict at the top level. It's the inverse of what people usually run into with const: typedef char *char_ptr means const char_ptr (or char_ptr const, they're equivalent) both mean "constant pointer to char" not "pointer to constant char" which is what people want. (See also this SO thread: C++ typedef interpretation of const pointers )

So in this case I think typedef int *pt does mean that restrict pt means int * restrict pt. It's pretty easy to verify because gcc will complain about "invalid use of 'restrict'" for restrict int *x but not for restrict pt x.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文