Issue with missing forward declaration in C++ [closed]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 06:14:59

问题


I have compiled following program without forward declaring function in C. It's successfully compiled and run in GCC without any warning or error.

#include <stdio.h>

int main()
{
        int ret = func(10, 5);
}

int func(int i, int j)
{
        return (i+j);
}

But, I have compiled following program without forward declaring function in C++, Compiler gives me an error.

#include <iostream>
using namespace std;

int main()
{
        int ret = func(10, 5);
}

int func(int i, int j)
{
        return (i+j);
}

An Error:

fl.cpp:6:22: error: ‘func’ was not declared in this scope
  int ret = func(10, 5);
                      ^

Why C++ Compiler Gives an Error? Is it not by default take int data type?


回答1:


Well, it is as much as wrong in C, as in C++.

Considering the question is based on the "assumption" that the code is valid from a C compiler point of view, let me elaborate that, as per the spec (C11), implicit declaration of functions is not allowed. Compile your code with strict conformance and (any conforming) compiler will produce the same error in C.

See live example

Quoting C11, Foreword/p7, "Major changes in the second edition included:"

  • remove implicit function declaration

and the same exist in the C99, also.


Note: On why it might have worked

Pre C99, there was actually room for this code to be compiled successfully. In case of a missing function prototype, it was assumed that the function returns an int and accepts any number of parameters as input. That is now very much non-standard and compilers with legacy support may choose to allow such code to be compiled, but strictly speaking, a conforming compiler should refuse to do so.




回答2:


Why C++ Compiler Gives an Error?

Because you shall not call functions that have not been declared in C++.

Is it not by default take int data type?

No. That used to be the case in another language, C. It is not the case in C++ (nor in C since later standard versions).




回答3:


In C++ you can't call an undeclared function. In C you can call a function without a forward declarator if the definition of the function returns an int. This is because of the old K&R function definition style. This is obsolete for ANSI-C, always declare a function with a prototype.




回答4:


To complete the picture and in relation to the answer by Sourav Ghosh. Here's what the C++ standard has to say about the issue:

[expr.call] p2:

[ Note: If a function or member function name is used, and name lookup does not find a declaration of that name, the program is ill-formed. No function is implicitly declared by such a call.  — end note ]

Couldn't get more explicit than that.



来源:https://stackoverflow.com/questions/42804326/issue-with-missing-forward-declaration-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!