C 用 typedef 限制
我现在正在做一些代码,但使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
确保您使用编译器的 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.快速浏览并阅读这个类似的SO问题,代码将是,如关键字“restrict”不是 C++ 编译器中的保留关键字,如上面链接中接受的答案所示,
__restrict
或__restricted__
,再次检查您的编译器...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...您需要一个“指向整数的受限制指针”
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 withconst
:typedef char *char_ptr
meansconst char_ptr
(orchar_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 thatrestrict pt
meansint * restrict pt
. It's pretty easy to verify because gcc will complain about "invalid use of 'restrict'" forrestrict int *x
but not forrestrict pt x
.