0
void sum(int n)
{
    sum1(n);
}
void sum1(int n)
{
    cout<<n;
}
int main()
{
    cout<<sum(7);
    return 0;
}

This code is giving an error that - sum1 was not declared in this scope.

In C++,why this is giving such an error?

orphius
  • 37
  • 5
  • You need to either add a prototype for `sum1` before `sum` or move the function before `sum`. – Retired Ninja Apr 12 '22 at 05:37
  • @RetiredNinja,But why I need that,I need to know an elaborative explanation.It doesn't occur in C,but why in c++? – orphius Apr 12 '22 at 05:39
  • 1
    It occurs in C as well, but in earlier versions of C there would be an implicit declaration. [Implicit function declarations in C](https://stackoverflow.com/questions/9182763/implicit-function-declarations-in-c) The compiler reads from the top down. If it hasn't seen a declaration or definition of something before it is used there's an error. – Retired Ninja Apr 12 '22 at 05:43
  • 1
    In C, 'implicit declarations' are generally allowed, however somewhat frowned upon, because the compiler doesn't know anything about the return type or the arguments of the function. C++ is more strict in this regard. If the function was not declared previously, it is a syntax error, period. The ability to overload functions may have factored into this decision. – Refugnic Eternium Apr 12 '22 at 05:44
  • @RefugnicEternium,can you elaborate your point on overload functions? – orphius Apr 12 '22 at 05:58
  • Regarding overloaded functions, lets say you have `void sum1(float f) { ... }` defined (or at least declared) before the `sum` function. Then `sum1(n)` would cause a conversion of `n` to a `float` value, and call the floating point function, instead of the integer function. Which might not be correct. – Some programmer dude Apr 12 '22 at 06:05
  • Can anybody please explain why this is giving specifically this scope error ? – orphius Apr 12 '22 at 06:12
  • It has been explained, several times. A function must be declared or defined before it can be called. – Retired Ninja Apr 12 '22 at 06:26

0 Answers0