c++ - c中的非可移植符号整数

标签 c++ c algorithm

以下内容摘自Writing solid code , 第 115 页。

int strcmp( const char *strLeft, const char *strRight )
{
  for( NULL; *strLeft == *strRight; strLeft ++ ,strRight ++ )
      if( strLeft == ‘\0’ ) 
          return(0);
  return ( (*strLeft<*strRight)?-1:1 );
}

The moment you use <, or any other operator that use sign information, you force the compiler to generate nonprtable code

它(粗线)是什么意思?这个我知道

  1. 右移符号整数是不可移植的。
  2. 比较有符号整数和无符号整数是不可移植的

为什么比较两个有符号整数是不可移植的?

最佳答案

C 中的“char”类型可以是有符号的或无符号的。所以在这里,如果字符串是 {0x81, 0} 和 {0x32, 0},那么如果 chars 有符号,0x81 将被解释为负数(结果将是第一个字符串比较少),如果 chars 是unsigned 它将被解释为正数(因此第二个字符串比较少)。这是不可移植的,因为结果因您使用的编译器而异。

关于c++ - c中的非可移植符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8463367/

相关文章:

c++ - pthread_cancel后"terminate called without an active exception"

c++ - 在opencv c++中旋转回图像

c++ - 移动立方体、体素,需要一些建议

algorithm - 适用于计算累进税的数据结构

algorithm - 证明堆生成排列的算法

c++ - 从 HDC 读取像素

c - 具有不同功能的线程之间的互斥锁

使用无符号字符的凯撒密码函数?

c - 如何用 C 创建 BACnet 客户端

c - 中央枢轴元素不起作用的快速排序算法