ANSI C 或 ISO C 是否指定 -5 % 10 应该是什么?
我似乎记得 ANSI C 没有指定当模运算符的任一操作数为负时应返回什么值(只是它应该一致)。是后来指定的,还是一直指定的但我记错了?
I seem to remember that ANSI C didn't specify what value should be returned when either operand of a modulo operator is negative (just that it should be consistent). Did it get specified later, or was it always specified and I am remembering incorrectly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C89,不完全(§3.3.5/6)。它可以是 -5 或 5,因为 -5 / 10 可以返回 0 或 -1(
%
是根据涉及/
、的线性方程定义的*
和+
):C99,是的(§6.5.5/6),结果必须是-5:
类似地,在 C++98 中,结果是实现定义的 (§5.6/4),遵循 C89 的定义,但提到舍入-零规则是首选,
事实上,它成为 C++0x 中的标准规则 (§5.6/4):
C89, not totally (§3.3.5/6). It can be either -5 or 5, because -5 / 10 can return 0 or -1 (
%
is defined in terms of a linear equation involving/
,*
and+
):C99, yes (§6.5.5/6), the result must be -5:
Similarly, in C++98 the result is implementation defined (§5.6/4), following C89's definition, but mentions that the round-towards-zero rule is preferred,
and indeed it becomes the standard rule in C++0x (§5.6/4):
为 KennyTM 的答案添加一些细节:如果 C 标准调用某种定义的实现,那么该实现需要来记录它所做的选择。通常这会在编译器或库文档中(手册页、帮助手册、印刷文档、CD 小册子:-)
任何声称符合 C89 或更高版本的实现都必须在某处提供此功能。
尝试寻找这样的文档。以
gcc
为例,它位于 gcc-info 中:To add a little detail to KennyTM's answer: If the C Standards call something implementation defined then that implementation is required to document the choice it makes. Usually this would be in the compiler or library documentation (man page, help manual, printed docs, CD booklet :-)
Any implementation claiming conformance to C89 or later must provide this somewhere.
Try looking for such a document. In the case of
gcc
for example, this is in the gcc-info: