比較運算符 (==  , !=  )的自動類型轉換

比較運算符 (==  , !=  )也會自動類型轉換,例如下面的代碼中語句 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));

}

 

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