GCC/G++ 的不同态度:void* 到 int

GCC/G++ different attitudes for: void* to int

本文关键字:void int 态度 同态 G++ GCC      更新时间:2023-10-16
#include<stdio.h>
void test(void *arg)
{
    if (arg != NULL)
    {
        int temp = (int *)arg;
        printf("[temp]%dn", temp);
    }
}
int main()
{
    int a = 3;
    int *b = &a;
    int t = b;
    test((void *)11);
    void * arg = (void *)22;
    int k = (int *)arg;//this statement  can not compaile  with G++,But GCC only Warning,why?(evernt use cpp rewrite it again)
    // int k=*(int *)arg;// why this statement not right?
    printf("[k]%dn", k);
    return 0;
}
int k = (int *)arg;

这个说法不能和G++兼容,但是GCC只是警告,为什么呢?

它不会在 C++ 中编译,因为int*不能隐式转换为 int,因此语句格式不正确。

// int k=*(int *)arg;

为什么这种说法不对?

该语句在C++的语法上格式良好。但是arg不指向int对象(或兼容类型的对象),因此通过指针进行间接的行为是不确定的。