在C语言中,调用未声明的函数是一种糟糕的风格(参见 这 )在C++中是非法的,使用不列出参数类型的声明向函数传递参数也是非法的。
null
如果我们在C语言中调用一个未声明的函数并对其进行编译,它将不会出现任何错误。但是,如果我们调用C++中未声明的函数,它就不会编译并生成错误。
在下面的示例中,代码在C中可以正常工作,
C
// C Program to demonstrate calling an undeclared function #include <stdio.h> // Argument list is not mentioned void f(); // Driver Code int main() { // This is considered as poor style in C, but invalid in // C++ f(2); getchar (); return 0; } void f( int x) { printf ( "%d" , x); } |
输出
2
但是,如果在C++中运行上面的代码,它将不会编译并生成错误,
C++
// CPP Program to demonstrate calling an undeclared function #include <bits/stdc++.h> using namespace std; // Argument list is not mentioned void f(); // Driver Code int main() { // This is considered as poor style in C, but invalid in // C++ f(2); getchar (); return 0; } void f( int x) { cout << x << endl; } |
输出
prog.cpp: In function ‘int main()’: prog.cpp:13:8: error: too many arguments to function ‘void f()’ f(2); ^ prog.cpp:6:6: note: declared here void f(); ^
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END