c99 之前的限制
考虑到这段代码,VC9 不会检测别名:
typedef struct { int x, y; } vec_t;
void rotate_cw(vec_t const *from,
vec_t *to)
{
/* Notice x depends on y and vice versa */
to->x = from->y;
to->y = -from->x;
}
/* ... */
vec_t a, b;
rotate_cw(&a, &b); /* OK, no aliasing */
rotate_cw(&a, &a); /* FAIL, aliasing is not detected */
明显的解决方法是使用临时的:
void rotate_cw(vec_t const *from,
vec_t *to)
{
int temp = from->x;
to->x = from->y;
to->y = -temp;
}
这是标准行为吗? 我期望编译器,除非被告知,否则会假设两个指针可能是别名。
Considering this code, VC9 doesn't detect aliasing :
typedef struct { int x, y; } vec_t;
void rotate_cw(vec_t const *from,
vec_t *to)
{
/* Notice x depends on y and vice versa */
to->x = from->y;
to->y = -from->x;
}
/* ... */
vec_t a, b;
rotate_cw(&a, &b); /* OK, no aliasing */
rotate_cw(&a, &a); /* FAIL, aliasing is not detected */
The obvious fix is to use a temporary :
void rotate_cw(vec_t const *from,
vec_t *to)
{
int temp = from->x;
to->x = from->y;
to->y = -temp;
}
Is this standard behavior ? I was expecting that the compiler, unless told so, would assume both pointers to be possibly aliased.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看此答案。
尝试将 __restrict 放在参数之前,似乎这是任何人发现让 MSVC 发出警告的唯一方法。
Check out this answer.
Try putting __restrict before the parameters, seems to be the only way anybody found of getting MSVC to give any warnings.
所编写的代码在 C89 或 C99 中完全有效。 它很晦涩,但是编译器没有什么可以诊断的,所以它不诊断。
如果您使用 C99 并对函数的两个参数进行“限制”,那么您将收到错误 - 如果您的编译器支持 C99。 AFAIK,当前版本的 MSVC 尚未完全支持 C99。
The code as written is perfectly valid, in C89 or C99. It is obscure, but there is nothing for the compiler to diagnose, so it doesn't diagnose.
If you used C99 and 'restrict' on both parameters of the function, then you would get an error - if your compiler supports C99. AFAIK, no current version of MSVC yet supports C99 fully.
在 C99 发明
restrict
限定符之前,一些 C 编译器包含优化选项,这些选项将指导它们对指针的使用做出某些假设; 我见过的此类编译器的手册明确警告说,此类优化不符合标准,并且可能会任意导致使用某些特定构造的代码,这些特定构造的行为由标准定义,其行为方式是违背了标准和程序员的意图。 从手册的角度来看,优化告诉编译器编译 C 的子集,该子集没有定义 C 中定义的某些极端情况的行为,但它将允许为那些情况生成更有效的代码。确实定义了。Before C99 invented the
restrict
qualifier, some C compilers included optimization options which would direct them to make certain assumptions about pointer usage; the manuals I've seen for such compilers expressly warned that such optimizations were not standards-compliant, and may arbitrarily cause code using certain particular constructs whose behavior was defined by the Standard to behave in a manner which was contrary to both the Standard and programmer intention. From the point of view of the manual, the optimizations told the compiler to compile a subset of C which did not define the behavior of certain corner cases that were defined in C, but which would allow the generation of more efficient code for those cases it did define.