ILD

C类型转换
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2025-2-20 站点:Inside Linux Development

Implicit type casting

C支持隐式转换:

1
2
short a = 10;
int b = a;


Explicit type casting

显示转换:

1
2
3
4
5
6
7
8
9
10
11
        signed char a = -1;
        unsigned char b = -1;
        if (a == b)
                printf("equal\n");
        else
                printf("not equal\n");
 
        if (a == (signed char)b)
                printf("equal\n");
        else
                printf("not equal\n");

打印

not equal

equal

此时需要显式转换。a == b,在做integer promotion时,一个是0扩展,一个是符号扩展,导致内容不一样。因此需要显式转换。


结论1:

    C,支持任何整数和浮点数类型的隐式转换。


指针类型转换

结论2:

    C支持void *指针和其它类型指针的相互隐式转换。

以下是合法的,不会给出编译警告:

1
2
        int *a = malloc(4);
        void *b = a;


结论3:

    C,非void *类型的指针需要显式转换

以下隐式转换,

1
2
        int *a = malloc(4);
        short *c = a;

编译器给除警告:

1
2
3
4
5
$ cc -c test.c
test.c: In function ‘main’:
test.c:8:13: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
  short *c = a;
             ^


结论4:

    C++,支持T*到void *类型的隐式转换,但不支持void *类型到T *类型的隐式转换。

代码:

1
2
        int *a = malloc(4);
        void *c = a;

第一个转换报错,第二个转换合法:

1
2
3
4
5
$ g++ test.c
test.c: In function ‘int main()’:
test.c:7:17: error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
  int *a = malloc(4);
                 ^



https://stackoverflow.com/questions/1736833/void-pointers-difference-between-c-and-c

https://softwareengineering.stackexchange.com/questions/275712/why-arent-void-s-implicitly-cast-in-c


Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.