c - 在确定数组大小时,括号是否有所不同?

标签 c arrays language-lawyer sizeof parentheses

以下程序在 gcc 4.8.2 上打印相同的数字两次:

#include <stdio.h>

int main()
{
    char a[13];
    printf("sizeof a  is %zu\n", sizeof a );
    printf("sizeof(a) is %zu\n", sizeof(a));
}

根据 this reddit post , gcc 在这方面不符合标准,因为带括号的表达式不在数组到指针衰减不会发生的异常(exception)列表中。

这个人是对的吗?这是相关的标准报价:

Except when it is the operand of the sizeof operator or the unary & operator, or is a character string literal used to initialize an array of character type, or is a wide string literal used to initialize an array with element type compatible with wchar_t, an lvalue that has type 'array of type' is converted to an expression that has type 'pointer to type' that points to the initial member of the array object and is not an lvalue.

为了清楚起见,他认为 (a) 应该触发数组到指针的衰减,因为括号不在上面的列表中(sizeof 运算符,一元 & 运算符,字符串文字作为初始值设定项)。

最佳答案

看似多余的括号是否会影响程序的语义,是C标准中长期存在的问题,至今仍未得到充分解决。

通常声称 ((void*)0) 在技术上不是空指针常量,因为没有规则说带括号的空指针常量是空指针常量。

一些编译器对 char s[] = ("abc"); 发出错误,因为虽然字符数组可以从字符串文字初始化,但该规则不包括带括号的字符串文字.

类似的例子还有很多。你找到了其中之一。

据我所知,共识基本上是规则应该是 C++ 所做的,但 C 从未正式采纳过。 C++ 使带括号的表达式在功能上等同于未带括号的表达式,但有一些明确说明的异常(exception)情况。这将同时涵盖所有这些问题。

所以从技术上讲,这个人可以被认为是正确的,但这是对没有人真正遵循的标准的过于严格的解释,因为众所周知,该标准在这里完全是错误的。

关于c - 在确定数组大小时,括号是否有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557710/

相关文章:

c - 编译 libPNG 示例时 undefined reference

ios - 错误 : index beyond bounds

java - 三元运算符无法识别 Eclipse 中的编译错误

c++ - 属性说明符序列是否继承?

C语言中的子父关系和继承

C程序读取和存储字符串

C++ 无法打开 lib 文件

MySQL 和推送查询数组在一起

javascript - 配对多个 JavaScript 数组

c++ - 为什么 std::unique_ptr operator* 会抛出而 operator-> 不会抛出?