静态 unsigned int foo 以及以后的 if ( foo >0 )?
书上说写:
static unsigned int foo;
andlater
if( foo > 0)
{
是错误的,而且会导致很难发现的bug。 这是为什么?
在 x86 汇编语言编程中,有符号算术指令和 还有无符号算术指令, JG JL <-有符号算术 JB JA <-无符号指令。
因此编译器可以用无符号指令组装 if (foo >0 ) 语句 不是吗?有人可以提前解释一下它是如何工作的吗?
那个指令有错吗?或者,如果“C”中存在差异,而“C++”在以下方面是严格的: 那件事呢?请解释一下。
在这里,我们将无符号变量与立即值进行比较。里面发生了什么 编译器实际上在这种情况下吗?
当我们比较有符号值和无符号值时会发生什么?那么编译器会选择什么指令,有符号指令还是无符号指令?
- 提前致谢 -
The book told that writing:
static unsigned int foo;
and later
if( foo > 0)
{
is wrong, and it will leads to a hard to find bug.
Why is that?
In the x86 assembly language programming there are signed arithmetic instructions and
also unsigned arithmetic instructions,
JG JL <-signed arithmetic
JB JA <- unsigned instructions.
So the compiler can just assemble that if (foo >0 ) statement with unsigned instructions
isn't it? Can somebody explain how it works in advance?
Is that instruction wrong? Or if there is a difference in "C" where "C++" is strict in
that case? Please explain.
Here we are comparing a unsigned variable with a immediate value. What is happening inside
the compiler actually in this case?
And when we compare a signed value with unsigned value what happens? Then what instructions will compiler choose, signed instructions or unsigned instructions?
--thanks in advance--
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题不应该在汇编程序层面上回答,而应该在c/c++语言层面上回答。在大多数体系结构上,无法比较有符号数和无符号数,并且 c/c++ 不方便进行此类比较。相反,存在有关将其中一个操作数转换为另一个操作数的类型以便进行比较的规则 - 例如参见 这个问题
关于与文字进行比较 - 典型的做法(就像你所做的那样)并没有错,但你可以做得更好 - 根据 c++ 标准:
如果您想确定您的文字类型(以及比较类型),请添加描述的后缀以确保文字类型正确。
还值得注意的是,文字
0
实际上不是十进制而是八进制 - 它似乎没有改变任何东西,但很出乎意料 - 或者我错了?总而言之 - 编写这样的代码并没有错,但您应该记住,在某些情况下,可能会表现出反直觉的行为(或者至少是反数学的;)
This question should not be answered on the level of assembler but stil on c/c++ language level. On most architectures it is impossible to compare signed and unsigned numbers, and c/c++ does not facilitate such comparisons. Instead there are rules about converting one of the operands to type of the other in order to compare them - see for example aswers to this question
About comparing to literals - typical way of doing it (as you did) is not wrong, but you can do it better - according to c++ standard:
If you want to be sure about your literal type (and therefore comaprison type) add described suffixes to ensure right type of literal.
It is also worth noticing that literal
0
is actually not decimal but octal - it doesn't seem to change anything, but is quite unexpected - or am I wrong?To summarize - it is not wrong to write code like that, but you should remeber that in certain conditions in might behave counter-intuitive (or at least counter-mathematical ;)