const 是否需要类型说明符?

发布于 2024-08-09 02:49:10 字数 286 浏览 1 评论 0原文

这里需要类型说明符吗?

const c = 7;

Bjarne Stroustrup 的“C++ 编程语言”第 80 页表示这是非法的。但是,我一直在练习一些 brainbench 测试,其中一个问题指出类型默认为 int 。 Brainbench 通常是正确的,因此我不确定哪个参考是正确的,并且我无法在标准中找到任何内容。有没有人有明确的答案和参考?

Is a type specifier required here?

const c = 7;

Bjarne Stroustrup's 'The C++ Programming Language' on page 80 says that this is illegal. However, I've been practicing some brainbench tests, and one of the questions states that the type defaults to int. Brainbench is usually correct, so I'm unsure of which reference is right, and I've been unable to find anything in the standard. Does anyone have a definitive answer and a reference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

网名女生简单气质 2024-08-16 02:49:10

默认类型 int 对于 C 有效,但对于 C++ 无效。即使在 C 语言中,也应该避免这种编码风格。另请注意,Bjarne Stroustrup 的书是标准 C++ 最权威的参考书之一。

The default type of int is valid for C, but not for C++. Even in C this style of coding should be avoided. Also note that Bjarne Stroustrup's book is one of the most authoritative reference for standard C++.

我早已燃尽 2024-08-16 02:49:10

对于 C++,除了标准之外,我更相信 Stroustrup。

也许问题是关于 C 而不是 C++?

第 7.1 节中的C++0x 标准草案。 6 说

声明中至少需要一个不是 cv 限定符的类型说明符,除非它声明了构造函数,
析构函数或转换函数。83 类型说明符序列不得定义类或枚举,除非它
出现在别名声明的 type-id 中 (7.1.3)。

For C++ I would believe Stroustrup over any place but a standard.

Perhaps the question was about C not C++?

The draft C++0x standard in section 7.1.6 says

At least one type-specifier that is not a cv-qualifier is required in a declaration unless it declares a constructor,
destructor or conversion function.83 A type-specifier-seq shall not define a class or enumeration unless it
appears in the type-id of an alias-declaration (7.1.3).

禾厶谷欠 2024-08-16 02:49:10

我无法说出标准......但只要看看像 const c = 7; 这样的语句,我就会尖叫出糟糕的代码风格。就编译器兼容性而言......它可能会时好时坏。 Microsoft Visual Studio 的编译器在编译 C++ 文件(.cpp 扩展名)时不会包含它的任何部分,但在编译 C 文件(.c 扩展名)时不会阻塞它,主要是因为 C 标准允许将变量默认为 < code>int 当未指定类型时。

I can't speak to the standard... but just looking at a statement like const c = 7; screams bad code style to me. As far as compiler compatibility... it's probably going to be hit-and-miss. Microsoft Visual Studio's compiler won't have any part of it when compiling a C++ file (.cpp extension) but doesn't choke on it when compiling a C file (.c extension) mainly because the C standard allows for defaulting variables as int when no type is specified.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文