看板 b94902HW 關於我們 聯絡資訊
今天接到一個求助問這個warning是怎麼回事: warning: comparison is always true due to limited range of data type 他說warning指的那一行是這樣寫的: while ( (data[n] = fgetc(infile)) != EOF) n++; 而data是unsigned char的陣列 這個是因為 EOF這個值在gcc裡其實是-1 但是這種寫法會拿 = 左邊的值去和EOF比 而 = 左邊是個unsigned char 但是unsigned char都是非負值 所以都不是-1 因而條件永遠成立 迴圈變成無窮迴圈 解決的方法有二: 一是多用一個int的變數 當做中介變數 用它接fgetc的回傳 再把它assign給陣列 二是利用feof函式 --- 另外還有一個求助是問: 11001010(0xCA) 它>>2之後為什麼是11110010(0xF2)? 不是應該是00110010(0x32)嗎? 這是因為所用的變數是signed(有號)的關係 signed變數最左邊的位元是用來記正負號的 0正1負 那>>在signed變數上是保持正負號 所以邊移邊填入正負號 因此左邊就全部變成1了 解決方法是使用unsigned char 這樣八個bit就都代表數值 所以>> <<移位時一律填0 這樣就沒事了 -- "Shan't say nothing if you don't say please," said Peeves in his annoying sing-song voice. "All right -- please." "NOTHING! Ha haaa! Told you I wouldn't say nothing if you didn't say please! Ha ha! Haaaaaa!" And they heard the sound of Peeves whooshing away and Filch cursing in rage. ---'Harry Potter and the Philisopher's Stone', P119 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.240.54
ericsk:這個我在實習課有講 12/17 23:54
Sinze:推一下 12/18 12:53