C语言类型转换有关问题

C语言类型转换问题
本帖最后由 Lengineer 于 2013-03-06 11:42:51 编辑
今天调程序遇到一个很神奇的问题

unsigned int get_be32(ByteIOContext *s)
{
int val;
val = get_be16(s) << 16;
val |= get_be16(s);
return val;//val值一样
}
unsigned int sample_rate=0;
情况1、  sample_rate=(get_be32(pb) >> 16);//sample_rate=-21...
情况2、  sample_rate=(unsigned int)get_be32(pb) >> 16;//44100正确
情况3、  sample_rate=get_be32(pb); sample_rate>>=16;//44100正确
这里为何要类型转换才行?

并且将上边函数改为
unsigned long get_be32(ByteIOContext *s)
{
long  val;
val = get_be16(s) << 16;
val |= get_be16(s);
return val;
}
现象一样
为何这里情况1、3会不同?
(我的vc6.0应该是int、long一样的)
语言 c

------解决方案--------------------
根据我的经验,是因为函数没有正确声明引起的,楼主请看下面的例子。

$ cat demo.c func.c

/**
 * @file        demo.c
 * @brief
 */

#include <stdio.h>

unsigned int get_be32(void *pb);

int main(int argc, char *argv[])
{
        void *pb;
        unsigned int sample_rate;

        sample_rate=(get_be32(pb) >> 16);
        printf("%d\n", sample_rate);
        sample_rate=(unsigned int)get_be32(pb) >> 16;
        printf("%d\n", sample_rate);
        sample_rate=get_be32(pb); sample_rate>>=16;
        printf("%d\n", sample_rate);

        sample_rate=(get_be32_not_declared(pb) >> 16);
        printf("%d\n", sample_rate);
        sample_rate=(unsigned int)get_be32_not_declared(pb) >> 16;
        printf("%d\n", sample_rate);
        sample_rate=get_be32_not_declared(pb); sample_rate>>=16;
        printf("%d\n", sample_rate);

        return 0;
}



/**
 * @file        func.c
 * @brief
 */

unsigned int get_be32(void *pb)
{
        return 0xAC441234;
}

unsigned int get_be32_not_declared(void *pb)
{
        return 0xAC441234;
}



$ gcc -o demo demo.c func.c && ./demo
44100
44100
44100
-21436
44100
44100
$ gcc -std=c99 -o demo demo.c func.c && ./demo
demo.c: In function 'main':
demo.c:22: warning: implicit declaration of function 'get_be32_not_declared'