1
#include <iostream>
using namespace std;
int my_variable = 12;
void cappy()
{
    std::cout<<"value is"<< my_variable<<endl;
}

int main()
{
std::cout<< my_variable<<endl;
cappy();
}

this c++ code work and returns:

12
value is12

but whereas :

#include <iostream>
using namespace std;
int my_variable = 12;

int main()
{
std::cout<< my_variable<<endl;
cappy();
}

void cappy()
{
    std::cout<<"value is"<< my_variable<<endl;
}

this code returns an error:

cpp: In function ‘int main()’:
cpp:8:7: error: ‘cappy’ was not declared in this scope

why is this so? does location of functions matter in c++?

Dishonored
  • 11
  • 2

2 Answers2

5

The function needs to be declared before it is used. Besides that, it doesn't matter. So you can have this:

void cappy(); // declaration

int main()
{
  cappy();
}

void cappy() // definition
{

}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

It happens because in c++ the compiler reads through the file once and isn't "smart enough to know" that this is a future function that is being called. So you could declare the function earlier, or make a header file declaring all the functions you will be using.