변수#
소개#
변수는 데이터를 저장하고 프로그램 전체에서 재사용 및 조작할 수 있도록 해줍니다. 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 — 정확도가 요구되는 수학 계산을 위한 고정밀 소수 숫자.
Float — 측정이나 계산에 유용한 표준 정밀도 소수입니다.
C 스타일 문자열 — 메시지, 레이블 또는 읽기 쉬운 출력을 표시하는 데 사용되는 텍스트 값입니다.
Boolean (bool) —
true또는false논리 및 의사 결정에 대한 값.배열 — 동일한 유형의 요소로 구성된 고정 크기 컬렉션입니다.
2D 배열 — 배열의 배열; 행, 그리드 또는 테이블과 같은 데이터를 표현하는 데 이상적입니다.
Const —
const로 선언된 변수는 수정할 수 없습니다.
변수 선언 및 할당#
C++에서 변수를 생성하려면 먼저 변수의 유형을 선언하고 그 뒤에 변수 이름을 입력한 다음, 선택적으로 = 연산자를 사용하여 값을 할당해야 합니다.
int distance = 100;
변수 이름을 지정할 때는 다음 규칙을 준수해야 합니다.
이름에는 특수 문자(예: 느낌표)를 포함할 수 없습니다.
이름은 숫자로 시작할 수 없습니다.
이름에는 공백을 사용할 수 없습니다.
이름은 미리 정의된 VEXcode 객체(예:
Drivetrain)와 충돌할 수 없습니다.이름은 C++ 예약어일 수 없습니다(예:
int,for등).변수 이름은 대소문자를 구분합니다(예:
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#
A float stores decimal numbers. In most VEX projects, doubles are preferred over floats unless memory usage is a concern.
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 스타일 문자열은 텍스트와 null 종료 문자를 저장할 수 있을 만큼 충분히 커야 합니다.
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);
}