Document 7
Document 7
int main(void)
{
g = 0;
}
• Only one instance of any name can exist at the same level:
int a;
int a;
is illegal.
GLOBAL VARIABLE: EXAMPLE 1
CODING OUTPUT
#include <iostream>
using namespace std;
void f(int, int);
int a = 3;
int main()
{
cout << a << endl;
f(a, 4);
}
void f(int x, int y)
{
x += a;
a += 2*y;
cout << x << " " << a << "\n";
}
GLOBAL VARIABLE: EXAMPLE 2
CODING OUTPUT
#include <iostream>
using namespace std;
void anotherFunction();
int num = 2;
int main() {
cout << "In main, num is " << num << "\n";
anotherFunction();
cout << "Back in main, num is " << num << "\n";
return 0;
}
void anotherFunction() {
cout << "In anotherFunction, num is " << num <<
"\n";
num = 50;
cout << "Now the num is " << num << "\n";
}
GLOBAL VARIABLE: EXAMPLE 3
CODING OUTPUT
#include <iostream>
using namespace std;
void printTwoNumbers(int, int);
int globalVar; //global variable declaration
int main(){
int a=5, b=10;
globalVar=99;
cout << "\nBefore, globalVar in main() is " << globalVar;
printTwoNumbers(a,b);
cout << "\nAfter, globalVar in main() is " << globalVar;
}
int SoftwareEngine(int m) m
{
m = m + 3; –4
return m;
}
EXAMPLE 2: PASS BY VALUE
CODING OUTPUT
#include <iostream>
using namespace std;
void test(int a);
int main()
{
int x = 50;
test(x);
cout << "Value x now is " << x;
return 0;
}
void test(int a)
{
a += 50;
}
EXAMPLE 3: PASS BY VALUE
CODING OUTPUT
#include <iostream>
using namespace std;
int security(int t);
int main()
{
int i = 0;
cout << " before call i = " << i << "\n";
i = security(i);
cout << " after call i = " << i << "\n";
return 0;
}
int security(int t)
{
t = t + 10;
return t;
}
EXAMPLE 4: PASS BY VALUE
CODING OUTPUT
#include <iostream>
using namespace std;
int num = 8;
void changeMe(int num);
int main()
{
num = 12;
cout << " In main: " << num << "\n";
changeMe (num);
cout << " In main:: " << num << "\n";
return 0;
}
void changeMe(int x)
{
num = 0;
x += num;
cout << " output is: " << x << "\n";
}
PASSING BY REFERENCE
• Passing a variable’s address is referred to as passing by reference
• Receiving function has access to memory location of the passed
variable
• Use ONLY when you want receiving function to change the contents
of variable
int main()
{
int x = 50;
test(x);
cout << "Value x now is " << x;
return 0;
}
void test(int &a)
{
a += 50;
}
EXAMPLE 3: PASS BY REFERENCE
CODING OUTPUT
#include<iostream>
using namespace std;
void passByRef(int &k);
int main() {
int i=0;
cout << "The value of i before call " << i << endl;
passByRef(i);
cout << "The value of i after call " << i << endl;
}
int main() {
int num = 12;
cout << "In main function, number is " << num;
changeMe(num);
cout << "\nBack in main again, number now is " << num;
return 0;
}