局部变量只有在自己所在的程序块内有效,也就是说如果你在函数内的一对大括号中定义一个局部变量,这个局部变量只在这个大括号范围内有效,出了大括号就失效了,不论他是否与程序块之外的变量重名。
同C语言的值传递一样,在调用函数时传入的变量值作为局部变量传入函数内部,不会改变这两个变量的值。
#include<iostream>
using namespace std;
void myFunction();
void swap(int,int);
int x=5,y=7;
int main()
{
cout << "x from main: "<< x <<endl;
cout << "y from main: " << y << endl<<endl;
myFunction();
cout << "\nBack from myFunction!"<<endl<<endl;
cout << "x from main: "<< x <<endl;
cout << "y from main: " << y << endl;
cout << "\n\n\n";
swap(x, y);
cout <<"x,y in the main:"<<x<<","<<y<<endl;
return 0;
}
void myFunction()
{
int y=10;
cout << "x from myFunction: "<< x<< endl;
cout << "y from myFunction: "<< y <<endl;
{
int y=20;
cout << " y in the block:"<<y<<endl;
}
cout<< "y again:"<<y<<endl;
}
void swap(int x,int y)
{
int temp ;
cout<<"\n swap in the function :"<<endl;
temp=x;
x=y;
y=temp;
cout<<"x,y in the function: "<<x<<","<<y<<endl;
}
运行结果:
x from main: 5
y from main: 7
x from myFunction: 5
y from myFunction: 10
y in the block:20
y again:10
Back from myFunction!
x from main: 5
y from main: 7
swap in the function :
x,y in the function: 7,5
x,y in the main:5,7