Scope of Functions

I've been studying functions for a while and have come across a big problem...
Consider the following program:
#include <conio.h>
#include <iostream>

using namespace std;
void order(int&,int&);
int main()
{
clrscr();
int n1=99,n2=11,n3=22,n4=88;
order(n1,n2);
order(n3,n4);
cout<<"n1= "<<n1<<endl;
cout<<"n2= "<<n2<<endl;
cout<<"n3= "<<n3<<endl;
cout<<"n4= "<<n4<<endl;
getch();
return 0;
}
void order(int& numb1,int& numb2)
{
if(numb1>numb2)
{
int temp=numb1;
numb1=numb2;
numb2=temp;
}
}

dis is fine bcoz d functions is declared outside main() i.e. , it has a global scope and it can be defined after main()....

Now consider d following program:

#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
clrscr();
void order(int&,int&);
int n1=99,n2=11,n3=22,n4=88;
order(n1,n2);
order(n3,n4);
cout<<"n1= "<<n1<<endl;
cout<<"n2= "<<n2<<endl;
cout<<"n3= "<<n3<<endl;
cout<<"n4= "<<n4<<endl;
getch();
return 0;
}
void order(int& numb1,int& numb2)
{
if(numb1>numb2)
{
int temp=numb1;
numb1=numb2;
numb2=temp;
}
}

in dis program order() is declared inside main()....

My Question is:-

When order has a local scope in d second program because it is defined inside main(), so how come it is defined outside main()???

Because defining a function outside main() (or any function for dat matter inside which it has been declared) means dat it has a global scope, whereas we are declaring it inside main() meaning dat it has a local scope???????
Last edited on
edit: see ascii's response.
Last edited on
The point of prototyping a function or class is so that the compiler knows it exists, even if it hasn't seen the definition. The first time you are globally prototyping the function, which means that anything defined after that prototype can use the order function without generating an error. In the second example, because you prototype the function in main, the prototype is only valid in the main function, which means that to call the order function from another function, you would either have to declare the prototype in the function that calls it, or the function would have to be defined after the order function. It's similar to a using declaration in this sense. For example this code would compile fine:
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

int main(void){
	cout << "Hello, world!" << endl;
	return 0;
}

void HelloWorld(void){
	cout << "Hello, world!" << endl;
	return;
}


But this would not:
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>

int main(void){
        using namespace std;
	cout << "Hello, world!" << endl;
	return 0;
}

void HelloWorld(void){
	cout << "Hello, world!" << endl;
	return;
}


Both of the examples you posted should compile, but there's no real reason to not make the function prototype global in the second example.
Last edited on
Topic archived. No new replies allowed.