比较运算符 (==  , !=  )的自动类型转换

比较运算符 (==  , !=  )也会自动类型转换,例如下面的代码中语句 newp[j] != (index & 0xFF)  , newp[j]会自动转换为int类型,还会进行符合扩展,使得本来期望是相等的结果不相等。语句 newp[j] != (char)(index & 0xFF) 进行了强制类型转换,比较的就是newp[j]的低8位,可以得到预期结果。也可以对newp[j] 进行强制类型转换,如 (unsigned char)newp[j] != (index & 0xFF) , 但是这时候必须是nsigned char.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<getopt.h>
#include <string.h>
int compare_no(char *newp, int index)
{
  for (int j = 0; j < 5; j++)
    if (newp[j] != (index & 0xFF))
      return 0;
  return 1;
}
int compare_yes(char *newp, int index)
{
  for (int j = 0; j < 5; j++)
    if (newp[j] !=(char) (index & 0xFF))
      return 0;
  return 1;

}

int main()

{
  char bp[5];
  int index = 0x1cc;
  memset(bp, index & 0xFF, 5);
  printf("%d\n", compare_no(bp, index));
  printf("%d\n", compare_yes(bp, index));

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章