変数#
導入#
変数はデータを格納し、プログラム全体でそのデータを再利用および操作できるようにします。C++は静的型付け言語であるため、変数を作成する際にその型を明示的に宣言する必要があります。宣言後に型を変更することはできません。例:
int angle = 90; // angle is an integer
char dist[] = "Distance"; // dist is an array of characters
double steps = 2.5; // steps is a double
C++は厳密な型付けを備えているため、明示的な型変換なしに互換性のない型に対して操作を実行することはできません。例えば、次のようになります。
int blocks = 2; // blocks is an integer
char rings[] = "4"; // rings is a string
int result = blocks + rings; // Creates a compilation error
このAPIでは、C++でよく使われる変数型について説明します。網羅的なリストではありませんが、実際に使用する可能性の高い型を網羅しています。
ローカル変数 — 関数内で宣言され、そのスコープ内でのみ使用されます。一時的な値や独立した値に最適です。
グローバル変数 — どの関数の外側でも宣言され、プロジェクト全体で使用されます。関数間でデータを共有するのに適しています。
整数 — 小数点を含まない、数えたり、距離を測ったりするために使用される整数。
Double — 正確さが求められる数学的計算のための高精度な10進数。
Float — 標準精度の10進数。測定や計算に役立ちます。
Cスタイルの文字列 — メッセージ、ラベル、または読みやすい出力の表示に使用されるテキスト値。
ブール値 (bool) —
trueまたはfalse論理と意思決定のための値。配列 — 同じ型の要素の固定サイズのコレクション。
2D配列 — 配列の配列。行、グリッド、またはテーブルのようなデータを表現するのに最適です。
Const — const
const変更できません。
変数の宣言と代入#
C++で変数を作成するには、まず型を宣言し、次に変数名を宣言し、必要に応じて = 演算子を使用して値を代入する必要があります。
int distance = 100;
変数に名前を付ける際には、以下の規則を遵守する必要があります。
名前には特殊文字(感嘆符など)を含めることはできません。
名前は数字で始めることはできません。
名前にはスペースを使用できません。
名前は、定義済みの VEXcode オブジェクト (例:
Drivetrain) と競合してはなりません。The name cannot be a C++ reserved keyword (e.g.,
int,for, etc.).変数名は大文字と小文字を区別します(例:
Distanceとdistanceは異なる変数です)。
Local Variables#
ローカル変数は、関数またはコードブロックの内部で定義されます。それらは、その関数またはコードブロックのスコープ内でのみアクセス可能であり、スコープ外からは参照できません。
関数を定義します (
int main()の外側)void show_local() { // This variable only exists inside this function int angle = 90; Brain.Screen.print("%d", angle); }関数を呼び出す
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code show_local(); }
ローカル変数は、特定の関数内またはプログラムの一部内でのみ有効な一時的な値を格納するためによく使用されます。
Global Variables#
グローバル変数は、関数やブロックの外側で定義されます。そのため、関数内を含め、プログラム内のどこからでもアクセスして読み取ることができます。
注: グローバル変数はプログラム内のどこからでもアクセスできるため、関数間でデータを共有するのに便利です。しかし、グローバル変数に過度に依存すると、プログラムのある部分で変数を変更すると、他の部分に予期しない影響を与える可能性があるため、意図しない副作用が発生する可能性があります。そのため、変数のスコープを定義された特定の関数に限定するローカル変数を可能な限り使用することが一般的に推奨されます。これにより、競合の可能性が減り、デバッグが容易になります。
関数を定義します (
int main()の外側)// The variable is defined outside a function int angle = 90; void show_global() { // You can access 'angle' inside a function Brain.Screen.print("%d", angle); Brain.Screen.newLine(); }関数を呼び出す
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code show_global(); Brain.Screen.print("%d", angle); }
C++では、グローバル変数は特別なキーワードを使わずに、関数内から直接アクセスして変更できます。ただし、同じ名前のローカル変数がある場合は、スコープ解決演算子 :: を使用してグローバル変数にアクセスできます。
関数を定義します (
int main()の外側)// Define the global variable int count = 0; void increase_count() { // Global variables can be accessed directly count = count + 1; Brain.Screen.print("Count: %d", count); Brain.Screen.newLine(); }関数を呼び出す
int main()int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Begin project code increase_count(); increase_count(); }
データの種類#
C++は、変数に格納できる様々なデータ型をサポートしています。一部の型は再代入が可能ですが、他の型では個々の要素を変更する必要があります。以下に、最も一般的に使用される型を示します。
Integer#
整数 (int) は小数点以下のない数です。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
int distance = 100;
// Move the robot forward for the variable value in mm
Drivetrain.driveFor(forward, distance, mm);
// Add to the variable and move forward the new value,
// for 200mm total
wait(1, seconds);
distance = distance + 100;
Drivetrain.driveFor(forward, distance, mm);
}
Double#
doubleとは、高精度(通常は64ビット)の小数点以下の桁を持つ数値のことです。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Store a value with decimal points
double raw_value = 0.88;
// Print the decimal value as a percentage
Brain.Screen.print("%.1f%%", raw_value * 100);
}
Float#
float は小数値を格納します。ほとんどの VEX プロジェクトでは、メモリ使用量が問題にならない限り、float よりも double が推奨されます。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Store a value with decimal points
float raw_value = 0.88;
// Print the decimal value as a percentage
Brain.Screen.print("%.1f%%", raw_value * 100);
}
String#
Cスタイルの文字列(char variable_name[])は、文字配列に格納された文字のシーケンスです。Cスタイルの文字列は、テキストとヌル終端文字を格納するのに十分な大きさでなければなりません。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Set the variable to a string then print the string
char message[] = "Ready!";
Brain.Screen.print(message);
}
Boolean#
ブール値(bool)は、 true または false 値を表します。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Set the state of the variable
bool delivered = false;
// Print different messages depending on the Boolean.
if (delivered) {
Brain.Screen.print("Package delivered!");
} else {
Brain.Screen.print("Delivering...");
}
}
ブール値はプロジェクトのどの段階でも変更できます。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Print the value of the delivered variable
bool delivered = false;
// Print different messages depending on the Boolean.
if (delivered) {
Brain.Screen.print("Package delivered!");
} else {
Brain.Screen.print("Delivering...");
}
wait(2, seconds);
// Clear the screen and print the value of the variable again
Brain.Screen.clearScreen();
Brain.Screen.setCursor(1,1);
delivered = true;
// Print different messages depending on the Boolean.
if (delivered) {
Brain.Screen.print("Package delivered!");
} else {
Brain.Screen.print("Delivering...");
}
}
Arrays#
配列は、インデックス0から始まる、同じ型の要素の固定サイズの集合です。配列の長さを把握し、作成時に宣言しておくのが良い習慣です。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Declare an array of 5 integers
int distances[5] = {100, 200, 150, 300, 250};
// Drive and turn 4 times to move the distance of the first four distances of the array
for (int i = 0; i < 4; i++) {
Drivetrain.driveFor(forward, distances[i], mm);
Drivetrain.turnFor(right, 90, degrees);
}
}
2D Arrays#
2次元配列は、グリッド、テーブル、または行列を表すためによく使用されます。各行は、特定のデータグループを表します。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Assign the values in the matrix 2D array
int matrix[3][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
// Loop through each row
for (int i = 0; i < 3; i++) {
// Loop through each column in the row
for (int j = 0; j < 3; j++) {
Brain.Screen.print("%d, ", matrix[i][j]);
}
Brain.Screen.newLine();
}
}
2次元配列内の特定の要素を変更できます。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Assign the values in the matrix 2D array
int matrix[3][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
// Modify the color (in column 2) in row 0
matrix[0][1] = 200;
// Print the modified row from the matrix 2D array
for (int j = 0; j < 3; j++) {
Brain.Screen.print("%d, ", matrix[0][j]);
}
}
Constant Variables#
const で宣言された変数は、初期化後に変更することはできません。
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
const int maxSpeed = 100;
// maxSpeed can be used like a normal variable
Drivetrain.setDriveVelocity(maxSpeed, percent);
}