考虑以下函数声明和定义。在头文件中:
void some_function(int param);
在源文件中:
#include "test.h"
void some_function(const int param) {}
int main(void) {
return 0;
}
在 Visual Studio 2010 下,编译为纯 C 项目,我看到
warning C4028: formal parameter 1 different from declaration
.但据我所知,这是完全有效的 C,而且是相当普遍的做法。我对此是否错了,因此 VS2010 是否正确警告我?或者,如果这是一个虚假警告,我是否可以专门针对这种情况禁用它,但在参数类型不匹配的实际情况下保持警告?
(VS2010 自带的实际编译器是:Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86。我的命令行只是
cl test.c
。)
最佳答案
C89 3.5.4.3 Function declarators
关于参数是这样说的:
For two function types to be compatible, both shall specify compatible return types. Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.
栏目
3.1.2.6 Compatible type and composite type
将兼容类型指定为具有相同类型的类型。它引用了 3.5.3
对于类型限定符(其中 const
是其中之一)并且指出:For two qualified types to be compatible, both shall have the identically qualified version of a compatible type; the order of type qualifiers within a list of specifiers or qualifiers does not affect the specified type.
现在你通常会认为
int
和 const int
是不兼容的类型。但是,我认为这是对标准的误读,因为 int
不是限定类型,因此上面的引用不适用。稍后在
3.5.4.3
中有更适用的报价。说明:For each parameter declared with qualified type, its type for these comparisons is the unqualified version of its declared type.
因此
int
和 const int
比较类似,应该允许。但这只是意味着根据标准,这不是错误。可能是微软,以他们的智慧,仍然认为这是一个可疑的行为,也是发出警告的一个很好的理由。即使您认为这是一个问题,Microsoft 也不太可能为您修复它(见下文)。
现在您可能想知道为什么在有更多现代标准可用时我要引用 C89。
这是因为 Microsoft 毫不掩饰 Visual C++ 主要是一个 C++ 编译器,并且只能将 C 代码编译为标准的早期迭代,根据 here。 :
Thanks for taking the time to send us your suggestion. Currently, there are no plans to implement C99 support in VS2010. Once we complete this product cycle, we will be reviewing all customer suggestions, including this one, for our future planning. - Mark Roberts, Microsoft.
而且,来自 wikipedia page :
According to Herb Sutter, the C compiler is only included for "historical reasons" and is not planned to be further developed. Users are advised to either use only the subset of the C language that is also valid C++, and then use the C++ compiler to compile their code, or to just use a different compiler such as Intel C++ Compiler or the GNU Compiler Collection instead.
这在 Herb Sutter 自己的博客,相关文章 here 中得到了证实。 :
We do not plan to support ISO C features that are not part of either C90 or ISO C++.
关于c - Visual Studio 的 C4028 警告(形式参数与声明不同)是虚假的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18524336/