从逗号列表中的空整数到指针的转换 [英] Conversion from null-integer to pointer in comma list

查看:172
本文介绍了从逗号列表中的空整数到指针的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在我们的现代世界中,NULL和0不是使用指针操作的最佳实践,并且根据cppreference:

I know that in our modern world NULL and 0 are not best practices in operating with pointers, and according to cppreference:


转换一个空指针常量(参见NULL),可以将
转换为任何指针类型,并且结果是空指针
该类型的值。这种转换(称为空指针转换)
允许转换为cv限定类型作为单个转换
,也就是说,它不被认为是数字和限定
转换的组合。

Pointer conversions A null pointer constant (see NULL), can be converted to any pointer type, and the result is the null pointer value of that type. Such conversion (known as null pointer conversion) is allowed to convert to a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions.

但是为什么不允许这个代码,gcc和clang会给我一个错误?

But why this code is not allowed and gcc with clang give me an error?

A* foo()
{
    return (bar(), NULL);
}




错误:无效从long int转换为A *

error: invalid conversion from long int to A*


推荐答案

这里的问题是

(bar(), NULL)

使用逗号运算符的表达式。


在逗号表达式E1,E2中,评估表达式E1,丢弃其结果,并且在表达式E2开始评估之前完成其副作用(注意,定义的运算符,不能保证顺序)。

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing).

逗号表达式的结果的类型,值和值类别正是类型,值和值第二个操作数类别E2 。如果E2是临时的,表达式的结果是临时的。如果E2是一个位字段,结果是一个位字段。

The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2. If E2 is a temporary, the result of the expression is that temporary. If E2 is a bit-field, the result is a bit-field.

所以类型 bar(),NULL)被确定为 long int ,因为它是 NULL 因此,它试图将 long int 转换为 NULL 的值为

So the type of (bar(), NULL) is being determined as a long int as that is the type of NULL So it is trying to convert a long int with the value of NULL to an A* which will fail.

如果我们将代码更改为

A* foo()
{
    return NULL;
}

这将编译为 NULL ,并且 NULL 的值可以分配给指针。

This will compile as the value of NULL is used and the value of NULL can be assigned to a pointer.

这篇关于从逗号列表中的空整数到指针的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆