Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c++ - Why the error of - calling the function before being declared, is not shown?

main()
{
    f();
}
int f( int i, float fl)
{
    printf("function");
}
  1. Why does the above code runs successfully in 'C' and prints function when it should report an error, as f () is being called before it is declared.

  2. When it's running successfully in 'C', then why not in 'C++'. When running in c++ it's showing: error: 'f' was not declared in this scope

  3. If it is because of something like the compiler assumes an undeclared function to return an int and accept an unspecified number of arguments, then why does it runs successfully for the function below too ( i.e. when returning the returning type to void instead of int ?

void f ( int i, float fl)

{

    printf("function");

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Because C allows the implicit declaration of functions. Or at least it did; C90 may require a declaration, I'm not sure. But since not declaring functions was common practice in C for such a long time, I would expect most compilers to continue to allow it, even after it is banned.

  2. Because C and C++ are different languages. C++ has never allowed implicitly declaring functions.

  3. Because historically, C didn't have a void type; functions with no return value were declared int, even if they didn't return anything, and there's no problem as long as you don't attempt to use the (non-existant) return value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...