char的定義在iOS和Android下是不同的


char is different in iOS and Android!
跨平台開發時很容易忽略的非常坑爹的一個區別。

我的需求是實現一個算法,這個算法在iOS和Android下需要保持一致的結果,很自然的我用C++實現了一份跨平台(cross-platform)代碼,在兩個平台都可以用,但這份代碼在iOS和Android下竟然出現了不同的結果,排查了很久后發現了這個不同:

iOS下char is signed,Android下char is unsigned
也就是說,在iOS下這兩個定義是等同的:

char cNum = 100;
signed char cNum = 100;

而在Android下這兩個定義是等同的:

char cNum = 100;
unsigned char cNum = 100;

當你用char進行運算的時候,signed和unsigned是有正負號差異的,會導致你的結果變得莫名其妙。

這個代碼在iOS和Android下代碼執行結果是不一樣的

char cNum = 0x80;
float fResult = cNum + 80;

解決方案:
聲明char類型的變量時,明確寫上是signed char還是unsigned char。

發現了問題之后,再反過來找資料的時候發現了這個,不得不感慨:問題總在解決之后突然就變得簡單了:
C Compiler differences for iOS and Android development

In your Android C implementation, char is unsigned, and the conversion from -7 in double to char is producing zero. (The behavior of this conversion when the value cannot be represented in the destination type is not defined by the C standard.)

In iOS, char is signed, and the conversion of -7 in double to char produces -7.

PS.

特別要說明下我的開發工具版本:
XCode:5.0.2
官方ADT:22.3.0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM