ARM上char类型问题

C标准表示char类型可以带符号也可以不带符号,由具体的编译器、处理器,或由它们两者共同决定到底char是带符号合适还是不带符号合适。大部分体系结构上,char默认是带符号的,它可以自-128到127之间取值。但也有一些例外,比如ARM体系结构上,char就是不带符号的,它的取值范围是0~255。

举例来说,默认char不带符号,下面的代码实际会把255而不是-1赋予i:
char i = -1;
而另一种机器上(微软WINCE),默认char带符号,就会确切地把-1赋予i。如果程序员本意是把-1保存在i中,那么前面的代码就该修改成:
signed char i = -1;
另外,如果程序员确实希望存储255,那么代码应该如下:
unsigned char = 255;
如果你在自己的代码中使用了char类型,那么你要保证在带符号和不带符号的情况下代码都没问题。如果你能明确要用的是哪一个,那么就直接声明它。

consider this simple program:

    > int main(void)
    > {
    >     char i = -1;
    >     printf("%d\n", i);
    >     return 0;
    > }

The print out is 255 in stead of -1, unless I define i as
signed char i;
then I get the “-1” print out.

The above code is actually buggy in that it assumes that the type “char” is equivalent to “signed char”. The C standards do say that “char” may either be a “signed char” or “unsigned char” and it is up to the compilers implementation or the platform which is followed. It is difficult to detect this code at compile time, since GCC does not issue any warnings. The only way to detect it is either by visual examination of the code, or by actually running it and finding a problem.

This causes problems on ARM based machines since “char” is of the “unsigned” variety, which allows the compiler to generate faster, more efficient code. ARM is not alone in this - SGI Mips running IRIX also encounters this problem.

However, dispite the lack of warning for the above case, GCC does warn with the following code:

        {
                char foo;
                foo = bar();
                if (foo == -1) {
                        ...
                }
        }

Code like the above will generate a compiler warning, which will be one of the following depending on the actual test used:
warning: comparison is always 0 due to limited range of data type
warning: comparison is always 1 due to limited range of data type
Please note however that the above warnings are not issued if “char” is “signed” and therefore can be difficult to pick up when compiling in such an environment.

下表说明了armcc和gcc编译器对arm文件所使用的数据类型的映射。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值