c++ - 在 C++ 中使用数组作为条件表达式是否有效?

标签 c++ arrays pointers

我有这个代码:

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 to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

有直接从裸指针到 bool 值的隐式转换;所以编译器选择它作为第二步,因为它允许立即达到所需的结果(转换为 bool 值)。

关于c++ - 在 C++ 中使用数组作为条件表达式是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8575555/

相关文章:

c - 提取所有内容直到遇到子字符串 C

c++ - 从 2 个 vector 的串联构造一个 vector

c++ - IAR 编译器中的指针

c - 仅在 eclipse 中出现此错误 "not a structure or union"

python - 根据索引和条件更改 numpy 数组中的值

c - 无法确定指针数组的大小

c++ - 在 Visual Studios 中创建 sqlite3.lib 文件/使用 sqlite3

c++ - 简单的双端队列初始化问题

java - 给一个arraylist另一个arraylist JAVA的值

c++ - Stroustrup 的 RAII 和强制转换运算符 FILE*() = 矛盾?