I recently picked up C++ and decided to try out making a function. However, I've run into a problem with my function func()
where, even if declared beforehand, it only works if it's placed before the main()
function.
If I place it after the main()
function, the system tells me there is "no matching function for call to func
".
Note: the functionfunc2
on the other hand works even if placed before or after the main()
function.
So here's the code :
#include <stdio.h>
#include <iostream>
void func2();
int func();
int main()
{
int y=2;
std :: cout << "Hello World\n" << func(y) << "\n";
func2();
return 0;
}
int func(int x)
{
x *= 2;
return x;
}
void func2()
{
std :: cout << "Hello there";
}
In C language, the declaration int func();
means a function with an unspecified number of arguments of any type, returning a int
.
In C++ language, the same declaration int func();
means a function without any arguments, returning a int
.
And therefore, in C++, the definition of func
with an argument of type int
is an overload. For the compiler, it is a different function, which in the original code is not declared before use, so an error is emitted.
But in C, it would be perfectly legal.
int func();
and
int func(int x)
See the difference? The first one should be
int func(int x);
You told the compiler that func
was a function with no arguments, then when you tried to call it with one argument the compiler said 'no matching function'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With