15. sample 2-01
// Global scope and static storage.
int a = 137;
// File scope and static storage.
static int b = 64;
void func() {
// Block scope and static storage.
static int c = 86;
// Block scope and template storage.
int d = 0;
}
int main() {
int x;
x = a; // OK.
x = b; // OK.
// x = c; // Compile error!
// x = d; // Compile error!
}
さまざまな変数
16. sample 2-02
// Lots and lots of variables...
int i, j, k, l, m, n;
double a, b, c;
void func1()
{
// ...
}
void func2()
{
// ...
}
int main()
{
func1();
func2();
}
悪い例
全部グローバル変数
にした
• どの変数がどこで使われているか
ぱっとみて分からない
分かりにくい
• 変数はプログラム終了まで
メモリ上に存在し続けることになる
メモリ効率が悪い
• 変数が増えてくると変数名が
重複する(衝突する)
大規模化できない
17. question 2-03
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
FILE* file;
int i;
char buffer[256];
int line_count = 0;
int main()
{
file = fopen("sample.txt", "r");
{
for (i = 0; !feof(file); i++)
{
fgets(buffer, sizeof(buffer) - 1, file);
printf(buffer);
++line_count;
}
}
fclose(file);
puts("");
printf("Number of lines is %d.¥n", line_count);
}
演習 2-3
次のプログラムを変数のスコープに気を付けてリファクタリングして下さい。
18. answer 2-03
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
int line_count = 0;
FILE* file = fopen("sample.txt", "r");
{
char buffer[256];
for (int i = 0; !feof(file); i++)
{
fgets(buffer, sizeof(buffer) - 1, file);
printf(buffer);
++line_count;
}
}
fclose(file);
puts("");
printf("Number of lines is %d.¥n", line_count);
}
演習 2-3
答え
33. sample 2-07
int main()
{
int x = 137;
int& r = x;
printf("Address of x is %p.¥n", &x);
printf("Address of r is %p.¥n", &r);
}
実行結果
Address of x is 0018F900.
Address of r is 0018F900.
参照の例 (1)
34. sample 2-08
#include <cstdio>
// swap function using pointer.
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// swap function using reference.
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
…
実行結果
x is 2, y is 1.
参照の例 (2)
→ポインタでできることの大半は、参照でもできる
39. question 2-05
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct S
{
double x, y, z;
};
void print(S* s)
{
printf("%lf, %lf, %lf¥n", s->x, s->y, s->z);
}
int main()
{
S s;
S* p = &s;
p->x = 0.0;
p->y = 1.0;
p->z = 2.0;
print(p);
}
演習 2-5
次のポインタで書かれたプログラムを参照を使ったプログラムに変換して下さい。
40. answer 2-05
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
struct S
{
double x, y, z;
};
void print(S& s)
{
printf("%lf, %lf, %lf¥n", s.x, s.y, s.z);
}
int main()
{
S s;
S& p = s;
p.x = 0.0;
p.y = 1.0;
p.z = 2.0;
print(p);
}
演習 2-5
答え
41. new/delete 演算子
new delete
オブジェクトを動的に生成する newで作成したオブジェクトを解放する
sample 2-13
struct S { /* ... */ };
int main()
{
int* x = new int();
delete x;
S* s = new S();
delete s;
}
42. new[]/delete[] 演算子
new[] delete[]
newの配列版 deleteの配列版
sample 2-14
struct S { /* ... */ };
int main()
{
int* x = new int[5];
delete[] x;
S* s = new S[5];
delete[] s;
}