# 參考

``````int n = 10;      // 定義變數
int *p = &n;     // 定義指標，儲存 n 的位址
int &r = n;      // 定義參考，是 n 的別名
``````

``````int &r; // error: 'r' declared as reference but not initialized
``````

``````#include <iostream>
using namespace std;

int main() {
int n = 10;
int &r = n;

cout << "n：" << n << endl
<< "r：" << r << endl;

r = 20;

cout << "n：" << n << endl
<< "r：" << r << endl;

return 0;
}
``````

``````n：10
r：10
n：20
r：20
``````

``````int n = 10;
int *p = &n;
int *&r = p; // 也就是 int* &r = p;
``````

``````int arr[] = {1, 2};
int (&r)[2] = arr;
``````

``````#include <iostream>
using namespace std;

int main() {
int maze[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

for(auto row : maze) {
for(int i = 0; i < 3; i++) {
cout << row[i] << "\t";
}
cout << endl;
}

return 0;
}
``````

``````#include <iostream>
using namespace std;

int main() {
int maze[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

for(int (*it)[3] = begin(maze); it < end(maze); it++) {
int *row = *it;
for(int i = 0; i < 3; i++) {
cout << row[i] << "\t";
}
cout << endl;
}

return 0;
}
``````

``````#include <iostream>
using namespace std;

int main() {
int maze[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

for(int (*it)[3] = begin(maze); it < end(maze); it++) {
int (&row)[3] = *it;   // 使用參考
for(auto offset = begin(row); offset < end(row); offset++) {
int n = *offset;
cout << n << "\t";
}
cout << endl;
}

return 0;
}
``````

``````#include <iostream>
using namespace std;

int main() {
int maze[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

for(auto &row : maze) {  // 使用參考
for(auto n : row) {
cout << n << "\t";
}
cout << endl;
}

return 0;
}
``````