変数の有効範囲
変数の有効範囲のことをスコープといいます。
- ファイルスコープ
- ファイルの中だけで有効なスコープ
- ブロックスコープ
- {}の中で有効なスコープ
- 関数スコープ
- 関数の引数の受け取りから、関数ブロックの最後まで有効なスコープ
- for文スコープ
- for文のカウンタ宣言から、forブロックの中だけで有効なスコープ
局所変数と大域変数
- "局所変数と大域変数"
#include <iostream> //scope 変数がどこから見えてどこから見えないかという分類 using namespace std; //どこのブロックにも属さない部分 //ファイルスコープ int d = 10;//d爆誕 大域変数、グローバル変数 //このへん int foo() { //変数宣言 コンパイラにa,bという整数の変数 //を使うことを伝える //変数は書いた順番通りに宣言さえる //宣言から下でしか使えない //ブロックスコープ int a = 5;//a爆誕 局所変数、ローカル変数 int b = 6;//b爆誕 return (a + b + d); }//a,b死亡 int main() { cout << foo() << endl; //fooはmainから可視 visible int c = foo();//c爆誕 cout << foo() << endl; }//c死亡 int foo2() { return(d); } //d死亡
スコープの話
- "スコープの話"
#include <iostream> using namespace std; //何回もやる処理などをまとめて書いて、後で呼び出す int plusAB(int a , int b)//関数スコープ { a = a + 8; return (a + b); }//引数a,b死亡 //aとbの値を入れ替える関数 void swap(int a, int b) { cout << "a:" << a << endl; cout << "b:" << b << endl; int c; c = a; a = b; b = c; cout << "a:" << a << endl; cout << "b:" << b << endl; }//a,b死亡 int main() { int input; int c = 3; cin >> input; //inputとcの値が、引数のaとbにコピーされて別物になってわたっている //cout << plusAB(input, c) << endl; cout << "input:" << input << endl; cout << "c=" << c << endl; swap(input, c); cout << "input:" << input << endl; cout << "c=" << c << endl; }