我有这个代码:
int main()
{
char buffer[10];
if( buffer ) {
return 1;
}
return 0;
}
Visual C++ 10 解释如下:buffer
衰减为指针,然后将指针与 null 进行比较。当使用/O2 编译时,检查被消除,代码等同于 return 1;
。
上面的代码有效吗? Visual C++ 是否正确编译它(我指的是衰减部分,而不是优化部分)?
最佳答案
C++11,6.4/4:
The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed.
所以标准说编译器必须执行任何隐式转换以将数组转换为 bool 值。将数组衰减为指针并将指针转换为 bool 值并通过针对 null 的相等性测试是一种方法,所以是的,程序定义明确,是的,它确实产生了正确的结果——显然,因为数组是在堆栈上分配,它衰减到的指针永远不会等于空指针。
更新:至于为什么遵循这两个转换链:
C++11, 4.2/1:
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.
因此,从数组类型到指向元素类型的指针的唯一合法转换。第一步没有选择。
C++11, 4.12/1:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.
有直接从裸指针到 bool 值的隐式转换;所以编译器选择它作为第二步,因为它允许立即达到所需的结果(转换为 bool 值)。
关于c++ - 在 C++ 中使用数组作为条件表达式是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8575555/