Search code examples
c++cforward-declarationfunction-prototypes

Issue with missing forward declaration in C++


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?


Solution

  • 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.