Professional Documents
Culture Documents
Shaobai Kan
chapter 5 (Continue...)
• Local variables.
— identifier declared inside a block has block scope.
• Global variables.
— identifier declared outside any function or class has
file scope.
# include <iostream>
using namespace std;
double square ( double );
int main( )
{
double i ;
Scope of variable i = 0.4 ;
i cout << square ( i ) << endl ;
return 0;
}
correct incorrect
int i ;
for ( int i = 1; i < 5 ; i ++)
cout << i << endl;
for ( i = 1; i < 5 ; i ++)
cout << i << endl;
# include <iostream>
using namespace std;
int GetValue ( void );
int main( )
{
cout << i << endl ;
Scope of variable cout << GetValue ( ) << endl ;
i
return 0;
}
stack
last in first out
# include <iostream>
using namespace std;
int Square ( int );
int main( )
{
for (int i =1; i <= 5; i++)
cout << Square(i) << endl ;
Function call
5 times return 0;
}
int Square ( int x)
{
int z;
z = x* x;
return z;
}
# include <iostream>
using namespace std;
return 0;
}
Rules.
1. When the function body is not too big and the function
call does happen frequently, we can try "inline".
x y
4 7
Algorithm ?
x y
7 4
Example
# include <iostream>
using namespace std;
int main( )
{
int x = 4, y = 7;
int t ;
t=x;
algorithm x=y;
y=t;
return 0 ;
}
Incorrect code
# include <iostream>
using namespace std;
void Swap( int x, int y );
int main( )
{
int x = 4, y = 7 ;
Passing arguments.
Passing arguments.
Correct code
# include <iostream>
using namespace std;
void Swap( int &x, int &y );
Pass-by-reference.
Alias
# include <iostream>
using namespace std;
int main( )
{
int intOne ;
int &rintOne = intOne ; //create and alias rintOne
intOne = 5;
cout << “intOne: ” << intOne << endl ;
cout << “rintOne: ” << rintOne << endl ;
rintOne = 7;
cout << “intOne: ” << intOne << endl ;
cout << “rintOne: ” << rintOne << endl ;
return 0;
}
Incorrect code
# include <iostream>
using namespace std;
int main( )
{
int x = 3 ;
bug int &y ; // Error: y must be initialized
y=x;
y = 7;
cout << “x = ” << x << endl << “y = ” << y << endl ;
return 0;
}