const 是否需要类型说明符?
这里需要类型说明符吗?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
默认类型 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++.
对于 C++,除了标准之外,我更相信 Stroustrup。
也许问题是关于 C 而不是 C++?
第 7.1 节中的C++0x 标准草案。 6 说
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
我无法说出标准......但只要看看像 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 asint
when no type is specified.