gpt4 book ai didi

c++ - 空指针之间的比较,它是定义的还是依赖于编译器的?

转载 作者:太空宇宙 更新时间:2023-11-04 14:49:27 25 4
gpt4 key购买 nike

我尝试比较将 int 转换为 void* 的效果,甚至是它们之间的比较

int i=1,j=2;
float a=1.1;

if((void *)i > (void *)j )
cout<<"i>j"<<endl;
else
cout<<"i<j"<<endl;

输出是

i<j

但是这个

if((void *)a > (void *)i )
cout<<"a>i"<<endl;
else
cout<<"a<i"<<endl;

报错

 error: invalid cast from type ‘float’ to type ‘void*’

我认为我们可以将任何东西转换为 void 指针?不是这样吗?

最佳答案

comparison between void pointer, is it defined or compiler dependent?

这是明确定义的,但结果通常是未指定的,如 C++11 5.9/3 所述:“如果两个指针表示相同的地址或都是空指针值,则如果运算符,则结果为真为 <= 或 >=,否则为假;否则结果未指定。”

请注意,std::less 和 friend 需要为指针定义总顺序,即使内置运算符没有。

但是,使用从任意整数值转换而来的指针做任何事情都会产生未定义的行为。

I thought we can cast any thing to void pointers?Is it not so?

没有。 reinterpret_cast(或等效的 C 风格转换)可以在指针和整数类型之间进行转换。将浮点值转换为指针毫无意义。

关于c++ - 空指针之间的比较,它是定义的还是依赖于编译器的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com