c++ - Static unsigned int foo 和后来的 if ( foo >0 )?

标签 c++ c int

这本书讲述了这样的写作:

static unsigned int foo;

以后

if( foo > 0)
{

是错误的,它会导致一个很难发现的错误。 这是为什么?

在 x86 汇编语言编程中,有带符号的算术指令和 还有无符号算术指令, JG JL <-符号算术 JB JA <- 未签名指令。

所以编译器可以用无符号指令组装 if (foo >0 ) 语句 不是吗?有人可以提前解释一下它是如何工作的吗?

这个指令错了吗?或者如果“C”中的“C++”是严格的 那个案子?请解释。

这里我们比较一个无符号变量和一个立即数。里面发生了什么 在这种情况下实际上是编译器?

当我们比较有符号值和无符号值时会发生什么?那么编译器会选择什么指令,有符号指令还是无符号指令?

--提前致谢--

最佳答案

这个问题不应该在汇编程序级别上回答,而应该在 c/c++ 语言级别上回答。在大多数体系结构上,不可能比较有符号数和无符号数,并且 c/c++ 不支持此类比较。相反,有关于将一个操作数转换为另一个操作数的类型以便比较它们的规则 - 例如参见 this question 的答案

关于与文字进行比较 - 典型的做法(就像你所做的那样)并没有错,但你可以做得更好 - 根据 c++ 标准:

2.13.1.1 An integer literal is a sequence of digits that has no period or exponent part. An integer literal may have a prefix that specifies its base and a suffix that specifies its type. The lexically first digit of the sequence of digits is the most significant. A decimal integer literal (base ten) begins with a digit other than 0 and con- sists of a sequence of decimal digits. An octal integer literal (base eight) begins with the digit 0 and con- sists of a sequence of octal digits.22) A hexadecimal integer literal (base sixteen) begins with 0x or 0X and consists of a sequence of hexadecimal digits, which include the decimal digits and the letters a through f and A through F with decimal values ten through fifteen. [Example: the number twelve can be written 12, 014, or 0XC. ]

2.13.1.2 The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has the first of these types in which its value can be represented: int, long int; if the value cannot be repre- sented as a long int, the behavior is undefined. If it is octal or hexadecimal and has no suffix, it has the first of these types in which its value can be represented: int, unsigned int, long int, unsigned long int. If it is suffixed by u or U, its type is the first of these types in which its value can be repre- sented: unsigned int, unsigned long int. If it is suffixed by l or L, its type is the first of these types in which its value can be represented: long int, unsigned long int. If it is suffixed by ul, lu, uL, Lu, Ul, lU, UL, or LU, its type is unsigned long int.

如果您想确定您的字面类型(以及同类型),请添加描述的后缀以确保字面类型正确。

还值得注意的是,字面量 0 实际上不是十进制而是八进制 - 它似乎没有改变任何东西,但却出乎意料 - 或者我错了吗?

总结一下——这样写代码并没有错,但你应该记住,在某些情况下,它的行为可能违反直觉(或者至少是反数学的;)

关于c++ - Static unsigned int foo 和后来的 if ( foo >0 )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7439268/

相关文章:

c++ - 具有 double 类型的可变数字参数的函数的奇怪输出

android - 如何检查除法的结果是int还是float

c# - 同时拥有 SonarQube 的 C++ 和 c# 插件会导致 SQL Server 出错

c++ - 如何在 C++ 中引用类结构中的函数?

c - __uint128_t 在 mingw gcc 上

c - 正弦的简单近似

java - 我可以将 long 类型的一维数组元素类型转换为 int 吗?

c - 将 int 数组转换为 short* 时,为什么为元素赋值会覆盖整个整数?

c++ - static assert c++ - 常量表达式错误

c++ - 在 Rcpp 中连接和列出