Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my C++ function, only when it's placed after main(), not work?

Tags:

c++

function

main

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";
}
like image 875
Giorgos Tsolakidis Avatar asked Dec 19 '20 12:12

Giorgos Tsolakidis


2 Answers

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.

like image 55
prapin Avatar answered Sep 23 '22 08:09

prapin


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

like image 22
john Avatar answered Sep 22 '22 08:09

john